pvjc24/cv5/program.c

70 lines
1.8 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
// function to compare two students based on their votes
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 {
// if the votes are the same, compare the names
return strcmp(student_a->name, student_b->name);
}
}
int main() {
// define an array of students with SIZE elements
struct student students[SIZE];
// initialize a variable to keep track of the size of the array
int size = 0;
// read in the student data from standard input
while (1) {
// allocate memory for the line
char line[SIZE];
memset(line, 0, SIZE);
char *r = fgets(line, SIZE, stdin);
// check if the line is empty
if (r == NULL) {
// end of input
break;
}
// parse the string and extract the number of votes and the student name
int votes;
if (sscanf(line, "%d %s", &votes, students[size].name) != 2) {
// error, the input was not in the expected format
// print an error message and exit
fprintf(stderr, "Error: invalid input format\n");
return 1;
}
students[size].votes = votes;
size++;
}
// sort the students based on their votes
qsort(students, size, sizeof(struct student), compare);
// print the results
printf("Results:\n");
for (int i = 0; i < size; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
}
return 0;
}