Initialization

This commit is contained in:
Kozar 2024-03-21 16:45:29 +01:00
parent 7a9d54c8c9
commit 851703535e

View File

@ -9,7 +9,7 @@ struct student {
int votes; int votes;
}; };
// function to compare two students based on their votes // porovnávacia funkcia pre zoradenie študentov
int compare(const void *a, const void *b) { int compare(const void *a, const void *b) {
struct student *student_a = (struct student *) a; struct student *student_a = (struct student *) a;
struct student *student_b = (struct student *) b; struct student *student_b = (struct student *) b;
@ -19,48 +19,47 @@ int compare(const void *a, const void *b) {
} else if (student_a->votes < student_b->votes) { } else if (student_a->votes < student_b->votes) {
return 1; return 1;
} else { } else {
// if the votes are the same, compare the names // ak majú rovnaký počet hlasov, porovnajte mená
return strcmp(student_a->name, student_b->name); return strcmp(student_a->name, student_b->name);
} }
} }
int main() { int main() {
// define an array of students with SIZE elements // definícia poľa študentov s veľkosťou SIZE
struct student students[SIZE]; struct student students[SIZE];
// initialize a variable to keep track of the size of the array // inicializácia premennej na uchovávanie veľkosti poľa
int size = 0; int size = 0;
// read in the student data from standard input // načítanie údajov o študentoch zo štandardného vstupu
while (1) { while (1) {
// allocate memory for the line
char line[SIZE]; char line[SIZE];
memset(line, 0, SIZE); memset(line, 0, SIZE);
char *r = fgets(line, SIZE, stdin); char *r = fgets(line, SIZE, stdin);
// check if the line is empty // kontrola, či je riadok prázdny
if (r == NULL) { if (r == NULL || (r[0] == '\n' && strlen(r) == 1)) {
// end of input // koniec vstupu
break; break;
} }
// parse the string and extract the number of votes and the student name // rozparsovanie riadku a extrakcia počtu hlasov a mena študenta
int votes; int votes;
if (sscanf(line, "%d %s", &votes, students[size].name) != 2) { if (sscanf(line, "%d %s", &votes, students[size].name) != 2) {
// error, the input was not in the expected format // chyba, vstup nebol v očakávanom formáte
// print an error message and exit // vypíšte chybovú správu a ukončite program
fprintf(stderr, "Error: invalid input format\n"); fprintf(stderr, "Chyba: neplatný formát vstupu\n");
return 1; return 1;
} }
students[size].votes = votes; students[size].votes = votes;
size++; size++;
} }
// sort the students based on their votes // zoradenie študentov podľa počtu hlasov
qsort(students, size, sizeof(struct student), compare); qsort(students, size, sizeof(struct student), compare);
// print the results // výpis výsledkov
printf("Results:\n"); printf("Výsledky:\n");
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
printf("%d %s\n", students[i].votes, students[i].name); printf("%d %s\n", students[i].votes, students[i].name);
} }