pvjc24/cv5/program.c
2024-03-20 13:59:55 +01:00

68 lines
1.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100
#define MAX_NAME_LENGTH 100
typedef struct {
char name[MAX_NAME_LENGTH];
int votes;
} Student;
int compare_students(const void *a, const void *b) {
const Student *student1 = (const Student *)a;
const Student *student2 = (const Student *)b;
if (student1->votes != student2->votes) {
return student2->votes - student1->votes;
} else {
return strcmp(student1->name, student2->name);
}
}
int main() {
char line[256];
Student students[MAX_STUDENTS];
int total_students = 0;
while (fgets(line, sizeof(line), stdin)) {
int votes;
char name[MAX_NAME_LENGTH];
if (sscanf(line, "%d %99[^\n]", &votes, name) != 2) {
fprintf(stderr, "Error: Invalid input format.\n");
return 1;
}
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 (!found) {
if (total_students >= MAX_STUDENTS) {
fprintf(stderr, "Error: Too many students.\n");
return 1;
}
strcpy(students[total_students].name, name);
students[total_students].votes = votes;
total_students++;
}
}
qsort(students, total_students, sizeof(Student), compare_students);
printf("Outcome:\n");
for (int i = 0; i < total_students; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
}
return 0;
}