pvjc24/cv5/program.c

67 lines
1.7 KiB
C
Raw Normal View History

2024-03-21 12:38:59 +00:00
#include <stdio.h>
2024-03-21 15:43:03 +00:00
#include <stdlib.h>
#include <string.h>
2024-03-21 12:38:59 +00:00
2024-03-21 13:09:15 +00:00
#define SIZE 100
struct student {
char name[SIZE];
int votes;
};
2024-03-21 15:43:03 +00:00
2024-03-21 15:48:25 +00:00
// comparison function for sorting students
2024-03-21 15:43:03 +00:00
int compare(const void *a, const void *b) {
struct student *student_a = (struct student *) a;
struct student *student_b = (struct student *) b;
if (student_a->votes > student_b->votes) {
return -1;
} else if (student_a->votes < student_b->votes) {
return 1;
} else {
2024-03-21 15:48:25 +00:00
// if votes are the same, compare names
2024-03-21 15:43:03 +00:00
return strcmp(student_a->name, student_b->name);
}
}
int main() {
struct student students[SIZE];
int size = 0;
2024-03-21 15:48:25 +00:00
// read student data from standard input
2024-03-21 15:43:03 +00:00
while (1) {
char line[SIZE];
memset(line, 0, SIZE);
char *r = fgets(line, SIZE, stdin);
2024-03-21 15:48:25 +00:00
// check if the line is empty
2024-03-21 15:45:29 +00:00
if (r == NULL || (r[0] == '\n' && strlen(r) == 1)) {
2024-03-21 15:48:25 +00:00
// end of input
2024-03-21 15:43:03 +00:00
break;
}
2024-03-21 15:48:25 +00:00
// parse the string and extract number of votes and student name
2024-03-21 15:43:03 +00:00
int votes;
2024-03-21 15:48:25 +00:00
if (sscanf(line, "%d %[^\n]", &votes, students[size].name) != 2) {
// error, input was not in expected format
// print error message and exit
fprintf(stderr, "Error: invalid input format\n");
2024-03-21 15:43:03 +00:00
return 1;
}
students[size].votes = votes;
size++;
}
2024-03-21 15:48:25 +00:00
// sort students based on their votes
2024-03-21 15:43:03 +00:00
qsort(students, size, sizeof(struct student), compare);
2024-03-21 15:48:25 +00:00
// print the results
printf("Results:\n");
2024-03-21 15:43:03 +00:00
for (int i = 0; i < size; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
}
2024-03-21 15:49:30 +00:00
printf("\n");
2024-03-21 15:43:03 +00:00
return 0;
}