pvjc25/du4/program.c

81 lines
1.9 KiB
C

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