pvjc25/du4/program.c
2025-03-21 15:22:30 +01:00

85 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 100
struct student {
char name[SIZE];
int votes;
};
struct student databaza[SIZE];
int size = 0;
int find_student(const char* name) {
for (int i = 0; i < size; i++) {
if (strcmp(databaza[i].name, name) == 0) {
return i;
}
}
return -1;
}
int compare(const void* a, const void* b) {
struct student* s1 = (struct student*)a;
struct student* s2 = (struct student*)b;
if (s1->votes > s2->votes) return -1;
if (s1->votes < s2->votes) return 1;
return strcmp(s1->name, s2->name);
}
int main() {
char line[SIZE];
memset(databaza, 0, sizeof(databaza));
while (fgets(line, SIZE, stdin)) {
char* end;
int votes = strtol(line, &end, 10);
if (*end != ' ') {
printf("Chyba: Neplatny format vstupu!\n");
return 1;
}
end++;
if (*end == '\0' || *end == '\n') {
printf("Chyba: Neplatny format vstupu!\n");
return 1;
}
char name[SIZE];
memset(name, 0, SIZE);
strncpy(name, end, SIZE - 1);
name[strcspn(name, "\n")] = '\0';
int id = find_student(name);
if (id < 0) {
if (size >= SIZE) {
printf("Chyba: Databaza je plna!\n");
return 1;
}
strncpy(databaza[size].name, name, SIZE - 1);
databaza[size].votes = votes;
size++;
} else {
databaza[id].votes += votes;
}
}
if (size == 0) {
printf("Chyba: Nebol nacitany ziadny platny zaznam!\n");
return 1;
}
qsort(databaza, size, sizeof(struct student), compare);
printf("Vysledky:\n");
for (int i = 0; i < size; i++) {
printf("%d %s\n", databaza[i].votes, databaza[i].name);
}
return 0;
}