funguje
This commit is contained in:
parent
c50301b776
commit
361151dfd1
@ -10,7 +10,8 @@ struct Student {
|
||||
int votes;
|
||||
};
|
||||
|
||||
int read_students(struct Student students[], int max_students) {
|
||||
// Funkcia načíta študentov zo štandardného vstupu a sčíta ich hlasy
|
||||
int read_and_sum_votes(struct Student students[], int max_students) {
|
||||
int count = 0;
|
||||
while (count < max_students) {
|
||||
int votes;
|
||||
@ -18,18 +19,35 @@ int read_students(struct Student students[], int max_students) {
|
||||
if (scanf("%d %[^\n]", &votes, name) != 2) {
|
||||
break; // Koniec vstupu alebo chyba
|
||||
}
|
||||
strcpy(students[count].name, name);
|
||||
students[count].votes = votes;
|
||||
count++;
|
||||
|
||||
// Hľadáme, či už sme tento študent videli
|
||||
int found = 0;
|
||||
for (int i = 0; i < count; i++) {
|
||||
if (strcmp(students[i].name, name) == 0) {
|
||||
// Ak sme študenta našli, pridáme mu hlasy
|
||||
students[i].votes += votes;
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Ak sme študenta ešte nevideli, pridáme ho do zoznamu
|
||||
if (!found) {
|
||||
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;
|
||||
}
|
||||
|
||||
// Funkcia na porovnávanie študentov pre qsort
|
||||
int compare(const void *p1, const void *p2) {
|
||||
struct Student *s1 = (struct Student *)p1;
|
||||
struct Student *s2 = (struct Student *)p2;
|
||||
const struct Student *s1 = (const struct Student *)p1;
|
||||
const struct Student *s2 = (const 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;
|
||||
@ -40,17 +58,20 @@ int compare(const void *p1, const void *p2) {
|
||||
|
||||
int main() {
|
||||
struct Student students[MAX_STUDENTS];
|
||||
int count = read_students(students, MAX_STUDENTS);
|
||||
int count = read_and_sum_votes(students, MAX_STUDENTS);
|
||||
|
||||
if (count == 0) {
|
||||
printf("Chyba: Nepodarilo sa načítať žiadne dáta.\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Sčítanie hlasov pre každého študenta a výpis
|
||||
printf("Celkový počet hlasov pre každého študenta:\n");
|
||||
// Triedenie študentov
|
||||
qsort(students, count, sizeof(struct Student), compare);
|
||||
|
||||
// Výpis výsledkov
|
||||
printf("Vysledky:\n");
|
||||
for (int i = 0; i < count; i++) {
|
||||
printf("%s: %d\n", students[i].name, students[i].votes);
|
||||
printf("%d %s\n", students[i].votes, students[i].name);
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
Loading…
Reference in New Issue
Block a user