pvjc24/cv5/program.c

76 lines
1.7 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;
2024-03-21 17:18:40 +00:00
return 0;
2024-03-21 17:16:16 +00:00
}
}
if (pocetStudentov < MAX_STUDENTOV) {
strcpy(studenti[pocetStudentov].meno, meno);
studenti[pocetStudentov].hlasy = pocetHlasov;
pocetStudentov++;
2024-03-21 17:18:40 +00:00
return 0;
2024-03-21 17:16:16 +00:00
}
2024-03-21 17:18:40 +00:00
return 1;
2024-03-21 17:16:16 +00:00
}
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;
2024-03-21 17:18:40 +00:00
int validneZaznamy = 0;
2024-03-21 17:16:16 +00:00
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;
}
2024-03-21 17:21:50 +00:00
validneZaznamy = 1;
2024-03-21 17:16:16 +00:00
} else {
2024-03-21 17:24:45 +00:00
2024-03-21 17:16:16 +00:00
break;
}
}
2024-03-21 17:18:40 +00:00
if (!validneZaznamy) {
2024-03-21 17:24:45 +00:00
2024-03-21 17:18:40 +00:00
printf("Nepodarilo nacitat nic\n");
2024-03-21 17:21:50 +00:00
return 0;
2024-03-21 17:24:45 +00:00
}
2024-03-21 17:18:40 +00:00
2024-03-21 17:16:16 +00:00
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;
}