pvjc25/du4/program.c
2025-03-08 17:55:33 +01:00

83 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
#define MAX_COUNT_OF_STUDENTS 1000
#define NAME_LENGTH 100
#define LINE_SIZE 250
typedef struct {
char name[NAME_LENGTH];
int votes;
} Student;
Student createStudent(const char name[], int votes) {
Student student;
strncpy(student.name, name, NAME_LENGTH - 1);
student.name[NAME_LENGTH - 1] = '\0';
student.votes = votes;
return student;
}
int compare_students(const void *a, const void *b) {
const Student *studentA = (const Student *)a;
const Student *studentB = (const Student *)b;
if (studentA->votes != studentB->votes) {
return studentB->votes - studentA->votes;
}
return strcmp(studentA->name, studentB->name);
}
int main() {
char line[LINE_SIZE];
Student students[MAX_COUNT_OF_STUDENTS];
int count = 0;
while (fgets(line, LINE_SIZE, stdin) != NULL && line[0] != '\n') {
int count_of_vote = 0;
char name[NAME_LENGTH] = {0};
line[strcspn(line, "\n")] = '\0';
int i = 0;
while (isdigit(line[i])) {
count_of_vote = count_of_vote * 10 + (line[i] - '0');
i++;
}
if (line[i] != ' ') {
return 0;
}
i++;
strncpy(name, line + i, NAME_LENGTH - 1);
name[NAME_LENGTH - 1] = '\0';
bool found = false;
for (int j = 0; j < count; ++j) {
if (strcmp(name, students[j].name) == 0) {
students[j].votes += count_of_vote;
found = true;
break;
}
}
if (!found) {
students[count++] = createStudent(name, count_of_vote);
}
}
qsort(students, count, sizeof(Student), compare_students);
printf("Vysledky:\n");
for (int i = 0; i < count; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
}
return 0;
}