This commit is contained in:
Tančáková 2024-03-20 16:22:08 +01:00
parent faaa62019f
commit 07d2180c57

View File

@ -2,53 +2,78 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#define MAX_NAME_LENGTH 100
#define MAX_BUFFER_LENGTH 256
#define SIZE 100 #define SIZE 100
struct student { struct student {
char name[SIZE]; char name[SIZE];
int votes; int votes;
}; };
struct student database[SIZE];
memset(database, 0, SIZE * sizeof(struct student)); // Funkcia pre porovnanie dvoch študentov
int size = 0; int compare(const void *p1, const void *p2) {
char line[SIZE]; const struct student *s1 = (const struct student *)p1;
memset(line, 0, SIZE); const struct student *s2 = (const struct student *)p2;
char *r = fgets(line, SIZE, stdin);
if (r == NULL) { // Porovnanie počtu hlasov
// Nastal koniec vstupu if (s1->votes != s2->votes) {
} return s2->votes - s1->votes; // Zoradenie zostupne podla poctu hlasov
char *end = NULL; } else {
int value = strtol(line, &end, 10); // Ak maju rovnaky pocet hlasov, zoradime lexikograficky podla mena
if (value == 0) { return strcmp(s1->name, s2->name);
// Prevod sa nepodaril }
} }
// Pre pokračovanie získame meno študenta // Funkcia na hladanie studenta v databaze
char name[SIZE];
memset(name, 0, SIZE);
char *name_start = end + 1;
int name_length = strlen(name_start) - 1; // Nezahrňujeme koniec riadka
if (name_length > 0) {
memcpy(name, name_start, name_length);
} else {
// Nepodarilo sa načítať meno
}
int find_student(struct student *students, int size, const char *name) { int find_student(struct student *students, int size, const char *name) {
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
if (strcmp(students[i].name, name) == 0) { if (strcmp(students[i].name, name) == 0) {
return i; // Nájdený študent return i; // Student najdeny
} }
} }
return 0; // Študent nenájdený return -1; // Student nenajdeny
} }
int id = find_student(database, size, name);
if (id < 0) { int main() {
// struct student database[SIZE];
memset(database, 0, SIZE * sizeof(struct student));
int size = 0;
return 1;
char line[SIZE];
while (fgets(line, SIZE, stdin) != NULL) {
int votes;
char name[SIZE];
// Nacitanie hlasov a mena
if (sscanf(line, "%d %[^\n]", &votes, name) != 2) {
fprintf(stderr, "Chyba pri citani riadku: %s", line);
return 1;
}
// Hladanie studenta v databaze
int idx = find_student(database, size, name);
if (idx == -1) {
// Student nie je v databaze, pridame ho
if (size >= SIZE) {
fprintf(stderr, "Prekroceny limit databazy\n");
return 1;
}
strcpy(database[size].name, name);
database[size].votes = votes;
size++;
} else {
// Student je v databaze, pripocitame hlasy
database[idx].votes += votes;
}
}
// Zoradenie databazy
qsort(database, size, sizeof(struct student), compare);
// Vypis databazy
for (int i = 0; i < size; i++) {
printf("%d %s\n", database[i].votes, database[i].name);
}
return 0;
} }