pvjc24/cv5/program.c
2024-03-22 00:57:05 +00:00

71 lines
1.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
struct student {
char name[SIZE];
int votes;
};
int compare(const void* p1, const void* p2){
struct student* s1 = (struct student*)p1;
struct student* s2 = (struct student*)p2;
if (s1->votes != s2->votes)
return s2->votes - s1->votes;
else
return strcmp(s1->name, s2->name);
}
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;
}
}
return -1;
}
int main() {
struct student database[SIZE];
memset(database, 0, SIZE * sizeof(struct student));
int size = 0;
char line[SIZE];
while (fgets(line, SIZE, stdin)) {
char* end = NULL;
int votes = strtol(line, &end, 10);
if (votes == 0) {
fprintf(stderr, "Nepodarilo␣nacitat␣nic\n");
break;
}
if (*end != ' ') {
fprintf(stderr, "Nepodarilo␣nacitat␣nic\n");
break;
}
char name[SIZE];
strcpy(name, end + 1);
name[strlen(name) - 1] = '\0';
int index = find_student(database, size, name);
if (index == -1) {
strcpy(database[size].name, name);
database[size].votes = votes;
size++;
} else {
database[index].votes += votes;
}
}
qsort(database, size, sizeof(struct student), compare);
printf("Vysledky:\n");
for (int i = 0; i < size; ++i) {
printf("%d %s\n", database[i].votes, database[i].name);
}
return 0;
}