pvjc24/cv5/program.c

115 lines
2.5 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));
2024-03-13 11:37:24 +00:00
int prvyInput = 1;
2024-03-13 11:22:37 +00:00
2024-03-13 10:34:16 +00:00
while (1) {
memset(line, 0, SIZE);
char *r = fgets(line, SIZE, stdin);
if (r == NULL) {
2024-03-13 11:37:24 +00:00
if(prvyInput){
printf("Nepodarilo nacitat nic\n");
return 0;
}
else{
break;
}
2024-03-13 11:08:51 +00:00
}
if (strcmp(line, "\n") == 0) {
2024-03-13 11:37:24 +00:00
if (prvyInput) {
printf("Nepodarilo nacitat nic\n");
return 0;
} else {
continue;
}
2024-03-13 10:34:16 +00:00
}
int value = strtol(line, NULL, 10);
if (value == 0) {
2024-03-13 11:37:24 +00:00
if (prvyInput) {
2024-03-13 11:23:48 +00:00
printf("Nepodarilo nacitat nic\n");
2024-03-13 11:22:37 +00:00
return 0;
} else {
break;
}
2024-03-13 10:34:16 +00:00
}
2024-03-13 11:22:37 +00:00
2024-03-13 11:37:24 +00:00
prvyInput = 0;
2024-03-13 11:22:37 +00:00
2024-03-13 10:34:16 +00:00
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);
}