pvjc24/cv5/program.c

92 lines
2.1 KiB
C
Raw Normal View History

2024-03-13 10:34:16 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
struct student {
char name[SIZE];
int votes;
};
int find_student(struct student *students, int size, const char *name);
int compare(const void *p1, const void *p2);
struct student databaza[SIZE];
int size = 0;
char line[SIZE];
int main() {
memset(databaza, 0, SIZE * sizeof(struct student));
while (1) {
memset(line, 0, SIZE);
char *r = fgets(line, SIZE, stdin);
if (r == NULL) {
break;
}
int value = strtol(line, NULL, 10);
if (value == 0) {
printf("Zly format vstupu\n");
return 0;
}
char name[SIZE];
memset(name, 0, SIZE);
char *zaciatok_mena = strchr(line, ' ') + 1;
int velkost_mena = strlen(zaciatok_mena) - 1;
if (velkost_mena > 0) {
memcpy(name, zaciatok_mena, velkost_mena);
name[velkost_mena] = '\0';
} else {
printf("Nepodarilo sa nacitat meno\n");
return 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 id = find_student(databaza, size, name);
if (id < 0) {
strcpy(databaza[size].name, name);
databaza[size].votes = value;
size += 1;
} else {
databaza[id].votes += value;
}
}
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;
}
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 1;
} else if (s1->votes > s2->votes) {
return -1;
}
return strcmp(s1->name, s2->name);
}