#include #include #include #include #include #define SIZE 100 #define MY_ERROR_OUTPUT stderr // chybovy vystup struct student { char name[SIZE]; int votes; }; // porovnavacia funkcia pre qsort int compare_students(const void *a, const void *b) { const struct student *student_a = (const struct student *)a; const struct student *student_b = (const struct student *)b; // ak maju rovnaky pocet hlasov, porovnam podla abecedy if (student_a->votes != student_b->votes) { return (student_b->votes - student_a->votes); } // inak porovnam podla poctu hlasov return strcmp(student_a->name, student_b->name); } int check_line(char *line, int *votes, char *name) { // najdenie prvej medzery v retazci char *space = strchr(line, ' '); // kontrola, ci sa nasla medzera if (space == NULL) { return 0; // neplatny riadok } //string na cislo premena char *end; *votes = strtol(line, &end, 10); if (*votes == 0) { return 0; // premena sa nepodarila } // nastavenie ukazovatela name na miesto za prvou medzerou char *name_start = space + 1; // nacitanie mena memset(name, 0, SIZE); // vynulovanie pomocneho pola pre meno int name_size = strlen(name_start) - 1; // velkost mena ale uz bez konca riadka if (name_size > 0) { memcpy(name, name_start, name_size); } else { return 0; // nepodarilo sa nacítat meno } return 1; } // vyhladanie polozky v databaze int find_student(struct student *students, int size, const char *name) { for (int i = 0; i < size; i++) { if (strcmp(students[i].name, name) == 0) { return i; // ak najde studenta } } return -1; } int main() { struct student databaza[SIZE]; int size = 0; char line[SIZE]; int votes; char name[SIZE]; bool chyba = false; // nacítanie a kontrola formatu vstupu while (1) { char* r = fgets(line,SIZE,stdin); if (r == NULL){ printf("Nepodarilo nacitat nic\n"); chyba = true; break; } if(line[0] == '\n'){ break; } if (check_line(line, &votes, name) == 0) { printf("Neplatny format"); continue; // preskoci riadok a nacita dalsi } // ci sa student nachadza v databaze int id = find_student(databaza, size, name); if (id < 0) { // Ak student nie je v databaze ta ho pridaj if (size < SIZE) { strcpy(databaza[size].name, name); databaza[size].votes = votes; size++; } else { printf("Databaza je plna\n"); break; // ked je databaza plna break } } else { // ak je v databaze aktualizuj pocet hlasov databaza[id].votes += votes; } } // triedim studentov qsort(databaza, size, sizeof(struct student), compare_students); if (chyba == false){ printf("Vysledky:\n"); for (int i = 0; i < size; i++) { printf("%d %s\n", databaza[i].votes, databaza[i].name); } } return 0; }