pvjc24/cv5/program.c
2024-03-20 13:53:02 +01:00

71 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Structure to hold student information (name and votes)
typedef struct {
char name[100];
int votes;
} Student;
// Function to compare two students based on their votes and names
int compare_students(const void *a, const void *b) {
const Student *student1 = (const Student *)a;
const Student *student2 = (const Student *)b;
// Sort by number of votes in descending order
if (student1->votes != student2->votes) {
return student2->votes - student1->votes;
} else {
// If votes are equal, sort lexicographically by name
return strcmp(student1->name, student2->name);
}
}
int main() {
char line[256];
Student students[100];
int total_students = 0;
// Read votes from standard input
while (fgets(line, sizeof(line), stdin)) {
int votes;
char name[100];
// Parse votes and name from input line
if (sscanf(line, "%d %99[^\n]", &votes, name) != 2) {
fprintf(stderr, "Error: Invalid input format.\n");
return 1;
}
// Find if the student is already in the list
int found = 0;
for (int i = 0; i < total_students; i++) {
if (strcmp(students[i].name, name) == 0) {
students[i].votes += votes;
found = 1;
break;
}
}
// If student not found, add to the list
if (!found) {
strcpy(students[total_students].name, name);
students[total_students].votes = votes;
total_students++;
}
}
// Sort the list of students based on votes and names
qsort(students, total_students, sizeof(Student), compare_students);
// Print the outcome
printf("Outcome:\n");
for (int i = 0; i < total_students; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
}
return 0;
}