pvjc24/cv5/program.c

67 lines
1.5 KiB
C
Raw Normal View History

2024-03-21 17:16:16 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTOV 100
#define MAX_MENO 100
typedef struct {
char meno[MAX_MENO];
int hlasy;
} Student;
Student studenti[MAX_STUDENTOV];
int pocetStudentov = 0;
int pridajHlas(char* meno, int pocetHlasov) {
for (int i = 0; i < pocetStudentov; i++) {
if (strcmp(studenti[i].meno, meno) == 0) {
studenti[i].hlasy += pocetHlasov;
return 0;
}
}
if (pocetStudentov < MAX_STUDENTOV) {
strcpy(studenti[pocetStudentov].meno, meno);
studenti[pocetStudentov].hlasy = pocetHlasov;
pocetStudentov++;
return 0;
}
return 1;
}
int porovnaj(const void* a, const void* b) {
Student *studentA = (Student *)a;
Student *studentB = (Student *)b;
if (studentA->hlasy == studentB->hlasy) {
return strcmp(studentA->meno, studentB->meno);
}
return studentB->hlasy - studentA->hlasy;
}
int main() {
char riadok[150];
char meno[MAX_MENO];
int pocetHlasov;
while (fgets(riadok, sizeof(riadok), stdin)) {
if (sscanf(riadok, "%d %[^\n]s", &pocetHlasov, meno) == 2) {
if (pridajHlas(meno, pocetHlasov)) {
printf("Nepodarilo sa pridať hlas.\n");
return 1;
}
} else {
break;
}
}
qsort(studenti, pocetStudentov, sizeof(Student), porovnaj);
printf("Vysledky:\n");
for (int i = 0; i < pocetStudentov; i++) {
printf("%d %s\n", studenti[i].hlasy, studenti[i].meno);
}
return 0;
}