Initialization
This commit is contained in:
parent
2c59b0295e
commit
7a9d54c8c9
@ -1,7 +1,6 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
int main() {
|
#include <stdlib.h>
|
||||||
return 0;
|
#include <string.h>
|
||||||
}
|
|
||||||
|
|
||||||
#define SIZE 100
|
#define SIZE 100
|
||||||
|
|
||||||
@ -9,3 +8,62 @@ struct student {
|
|||||||
char name[SIZE];
|
char name[SIZE];
|
||||||
int votes;
|
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;
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user