pvjc25/du4/program.c

80 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_NAME 100
#define MAX_ENTRIES 100
typedef struct {
char *name;
int votes;
} Student;
Student *students[MAX_ENTRIES];
int student_count = 0;
Student *find_or_add(const char *name) {
for (int i = 0; i < student_count; i++) {
if (strcmp(students[i]->name, name) == 0) {
return students[i];
}
}
if (student_count < MAX_ENTRIES) {
Student *new_student = (Student *)malloc(sizeof(Student));
new_student->name = strdup(name);
new_student->votes = 0;
students[student_count++] = new_student;
return new_student;
}
return NULL;
}
int compare(const void *a, const void *b) {
Student *s1 = *(Student **)a;
Student *s2 = *(Student **)b;
return (s2->votes != s1->votes) ? (s2->votes - s1->votes) : strcmp(s1->name, s2->name);
}
void free_memory() {
for (int i = 0; i < student_count; i++) {
free(students[i]->name);
free(students[i]);
}
}
int main() {
char line[MAX_NAME + 10];
int votes;
char name[MAX_NAME];
int has_data = 0;
while (fgets(line, sizeof(line), stdin)) {
// Preskočí prázdne riadky
if (strlen(line) <= 1) continue;
if (sscanf(line, "%d %[^\n]", &votes, name) != 2 || votes < 0) {
continue; // Namiesto prerušenia len ignoruje neplatné riadky
}
Student *student = find_or_add(name);
if (student) student->votes += votes;
has_data = 1;
}
if (!has_data) {
printf("Nepodarilo nacitat nic\n");
return 1;
}
qsort(students, student_count, sizeof(Student *), compare);
printf("Vysledky:\n");
for (int i = 0; i < student_count; i++) {
printf("%d %s\n", students[i]->votes, students[i]->name);
}
free_memory();
return 0;
}