pvjc24/cv5/program.c

68 lines
1.7 KiB
C
Raw Normal View History

2024-03-13 09:55:11 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2024-03-20 12:59:55 +00:00
#define MAX_STUDENTS 100
#define MAX_NAME_LENGTH 100
2024-03-13 09:55:11 +00:00
typedef struct {
2024-03-20 12:59:55 +00:00
char name[MAX_NAME_LENGTH];
2024-03-13 09:55:11 +00:00
int votes;
2024-03-20 12:33:29 +00:00
} Student;
2024-03-13 09:55:11 +00:00
2024-03-20 12:33:29 +00:00
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;
2024-03-13 09:55:11 +00:00
} else {
2024-03-20 12:33:29 +00:00
return strcmp(student1->name, student2->name);
2024-03-13 09:55:11 +00:00
}
}
int main() {
2024-03-20 12:33:29 +00:00
char line[256];
2024-03-20 12:59:55 +00:00
Student students[MAX_STUDENTS];
2024-03-20 12:33:29 +00:00
int total_students = 0;
2024-03-13 09:55:11 +00:00
2024-03-20 12:33:29 +00:00
while (fgets(line, sizeof(line), stdin)) {
2024-03-13 09:55:11 +00:00
int votes;
2024-03-20 12:59:55 +00:00
char name[MAX_NAME_LENGTH];
2024-03-20 12:33:29 +00:00
if (sscanf(line, "%d %99[^\n]", &votes, name) != 2) {
fprintf(stderr, "Error: Invalid input format.\n");
2024-03-13 10:10:55 +00:00
return 1;
}
2024-03-20 12:33:29 +00:00
2024-03-13 09:55:11 +00:00
int found = 0;
2024-03-20 12:33:29 +00:00
for (int i = 0; i < total_students; i++) {
if (strcmp(students[i].name, name) == 0) {
students[i].votes += votes;
2024-03-13 09:55:11 +00:00
found = 1;
break;
}
}
2024-03-20 12:33:29 +00:00
2024-03-13 09:55:11 +00:00
if (!found) {
2024-03-20 12:59:55 +00:00
if (total_students >= MAX_STUDENTS) {
fprintf(stderr, "Error: Too many students.\n");
return 1;
}
2024-03-20 12:33:29 +00:00
strcpy(students[total_students].name, name);
students[total_students].votes = votes;
total_students++;
2024-03-13 09:55:11 +00:00
}
}
2024-03-20 12:33:29 +00:00
qsort(students, total_students, sizeof(Student), compare_students);
2024-03-20 12:53:02 +00:00
printf("Outcome:\n");
2024-03-20 12:33:29 +00:00
for (int i = 0; i < total_students; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
2024-03-13 09:55:11 +00:00
}
return 0;
}