pvjc24/cv5/program.c

71 lines
1.6 KiB
C
Raw Permalink Normal View History

2024-03-21 21:01:53 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2024-03-22 00:55:32 +00:00
#define SIZE 100
2024-03-21 21:01:53 +00:00
2024-03-22 00:55:32 +00:00
struct student {
char name[SIZE];
int votes;
};
2024-03-21 21:01:53 +00:00
2024-03-22 00:55:32 +00:00
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);
}
2024-03-21 21:01:53 +00:00
2024-03-22 00:55:32 +00:00
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;
2024-03-21 21:01:53 +00:00
}
int main() {
2024-03-22 00:55:32 +00:00
struct student database[SIZE];
memset(database, 0, SIZE * sizeof(struct student));
int size = 0;
2024-03-22 00:39:21 +00:00
2024-03-22 00:55:32 +00:00
char line[SIZE];
while (fgets(line, SIZE, stdin)) {
char* end = NULL;
int votes = strtol(line, &end, 10);
if (votes == 0) {
2024-03-22 00:57:05 +00:00
fprintf(stderr, "Nepodarilo␣nacitat␣nic\n");
2024-03-22 00:55:32 +00:00
break;
}
if (*end != ' ') {
2024-03-22 00:57:05 +00:00
fprintf(stderr, "Nepodarilo␣nacitat␣nic\n");
2024-03-22 00:55:32 +00:00
break;
}
char name[SIZE];
strcpy(name, end + 1);
name[strlen(name) - 1] = '\0';
2024-03-22 00:22:30 +00:00
2024-03-22 00:55:32 +00:00
int index = find_student(database, size, name);
if (index == -1) {
strcpy(database[size].name, name);
database[size].votes = votes;
size++;
2024-03-22 00:36:40 +00:00
} else {
2024-03-22 00:55:32 +00:00
database[index].votes += votes;
2024-03-22 00:32:24 +00:00
}
2024-03-22 00:29:34 +00:00
}
2024-03-22 00:22:30 +00:00
2024-03-22 00:55:32 +00:00
qsort(database, size, sizeof(struct student), compare);
2024-03-22 00:22:30 +00:00
2024-03-22 00:55:32 +00:00
printf("Vysledky:\n");
for (int i = 0; i < size; ++i) {
printf("%d %s\n", database[i].votes, database[i].name);
2024-03-22 00:36:40 +00:00
}
2024-03-22 00:22:30 +00:00
2024-03-22 00:36:40 +00:00
return 0;
2024-03-22 00:29:34 +00:00
}