diff --git a/cv5/program.c b/cv5/program.c index 80f59b7..0377801 100644 --- a/cv5/program.c +++ b/cv5/program.c @@ -1,7 +1,6 @@ #include -int main() { - return 0; -} +#include +#include #define SIZE 100 @@ -9,3 +8,62 @@ struct student { char name[SIZE]; int votes; }; + +// 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; +}