70 lines
1.9 KiB
C
70 lines
1.9 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define MAX_STUDENTS 100
|
|
#define MAX_NAME_LENGTH 50
|
|
|
|
struct Student {
|
|
char name[MAX_NAME_LENGTH];
|
|
int votes;
|
|
};
|
|
|
|
int read_students(struct Student students[], int max_students) {
|
|
int count = 0;
|
|
while (count < max_students) {
|
|
int votes;
|
|
char name[MAX_NAME_LENGTH];
|
|
if (scanf("%d %[^\n]", &votes, name) != 2) {
|
|
break; // Koniec vstupu alebo chyba
|
|
}
|
|
strcpy(students[count].name, name);
|
|
students[count].votes = votes;
|
|
count++;
|
|
// Zbavíme sa koncového znaku nového riadku z bufferu vstupu
|
|
getchar();
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
struct Student students[MAX_STUDENTS];
|
|
int count = read_students(students, MAX_STUDENTS);
|
|
|
|
if (count == 0) {
|
|
printf("Chyba: Nepodarilo sa načítať žiadne dáta.\n");
|
|
return 1;
|
|
}
|
|
|
|
// Triedenie študentov
|
|
qsort(students, count, sizeof(struct Student), compare);
|
|
|
|
// Výpis výsledkov
|
|
printf("Vysledky:\n");
|
|
int total_votes = 0; // Premenná pre uchovanie súčtu hlasov
|
|
for (int i = 0; i < count; i++) {
|
|
printf("%d %s\n", students[i].votes, students[i].name);
|
|
total_votes += students[i].votes; // Pridanie hlasov toho študenta k celkovému súčtu
|
|
}
|
|
|
|
// Výpis súčtu hlasov pre každého študenta
|
|
printf("\nSúčet hlasov pre každého študenta:\n");
|
|
for (int i = 0; i < count; i++) {
|
|
printf("%s: %d\n", students[i].name, students[i].votes);
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|