pvjc24/cv5/program.c

62 lines
1.5 KiB
C
Raw Normal View History

2024-03-22 07:38:38 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100
2024-03-22 07:49:29 +00:00
#define MAX_NAME_LENGTH 50
2024-03-22 07:38:38 +00:00
struct Student {
2024-03-22 07:49:29 +00:00
char name[MAX_NAME_LENGTH];
2024-03-22 07:38:38 +00:00
int votes;
};
int read_students(struct Student students[], int max_students) {
2024-03-22 07:49:29 +00:00
int count = 0;
while (count < max_students) {
2024-03-22 07:38:38 +00:00
int votes;
2024-03-22 07:49:29 +00:00
char name[MAX_NAME_LENGTH];
if (scanf("%d %[^\n]", &votes, name) != 2) {
break; // Koniec vstupu alebo chyba
2024-03-22 07:38:38 +00:00
}
2024-03-22 07:49:29 +00:00
strcpy(students[count].name, name);
students[count].votes = votes;
count++;
2024-03-22 07:51:27 +00:00
// Zbavíme sa koncového znaku nového riadku z bufferu vstupu
getchar();
2024-03-22 07:49:29 +00:00
}
return count;
}
int compare(const void *p1, const void *p2) {
struct Student *s1 = (struct Student *)p1;
struct Student *s2 = (struct Student *)p2;
// Porovnanie podľa počtu hlasov, v prípade rovnakého počtu podľa mena
if (s1->votes != s2->votes) {
return s2->votes - s1->votes;
} else {
return strcmp(s1->name, s2->name);
2024-03-22 07:38:38 +00:00
}
}
int main() {
struct Student students[MAX_STUDENTS];
2024-03-22 07:49:29 +00:00
int count = read_students(students, MAX_STUDENTS);
if (count == 0) {
printf("Chyba: Nepodarilo sa načítať žiadne dáta.\n");
return 1;
}
2024-03-22 07:38:38 +00:00
2024-03-22 07:49:29 +00:00
// Triedenie študentov
qsort(students, count, sizeof(struct Student), compare);
2024-03-22 07:38:38 +00:00
2024-03-22 07:49:29 +00:00
// Výpis výsledkov
2024-03-22 07:54:45 +00:00
printf("Vysledky:\n");
2024-03-22 07:49:29 +00:00
for (int i = 0; i < count; i++) {
2024-03-22 07:38:38 +00:00
printf("%d %s\n", students[i].votes, students[i].name);
}
return 0;
}