89 lines
2.2 KiB
C
89 lines
2.2 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define SIZE 100
|
|
|
|
struct student {
|
|
char name[SIZE];
|
|
int votes;
|
|
};
|
|
|
|
// comparison function for sorting students
|
|
int compare(const void *a, const void *b) {
|
|
struct student *student_a = (struct student *) a;
|
|
struct student *student_b = (struct student *) b;
|
|
|
|
if (student_a->votes > student_b->votes) {
|
|
return -1;
|
|
} else if (student_a->votes < student_b->votes) {
|
|
return 1;
|
|
} else {
|
|
// if votes are the same, compare names
|
|
return strcmp(student_a->name, student_b->name);
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
struct student students[SIZE];
|
|
int size = 0;
|
|
int successful_lines = 0; // Counter for successful lines read
|
|
|
|
// read student data from standard input
|
|
while (1) {
|
|
char line[SIZE];
|
|
memset(line, 0, SIZE);
|
|
char *r = fgets(line, SIZE, stdin);
|
|
|
|
// check if the line is empty
|
|
if (r == NULL || (r[0] == '\n' && strlen(r) == 1)) {
|
|
// end of input
|
|
break;
|
|
}
|
|
|
|
// parse the string and extract number of votes and student name
|
|
int votes;
|
|
char name[SIZE];
|
|
if (sscanf(line, "%d %[^\n]", &votes, name) != 2) {
|
|
if (successful_lines >= 1){
|
|
continue;
|
|
}
|
|
else{
|
|
printf("Nepodarilo nacitat nic\n");
|
|
break;
|
|
}
|
|
}
|
|
|
|
successful_lines++;
|
|
|
|
// check if this student already exists
|
|
int found = 0;
|
|
for (int i = 0; i < size; i++) {
|
|
if (strcmp(students[i].name, name) == 0) {
|
|
// add votes to existing student
|
|
students[i].votes += votes;
|
|
found = 1;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// if the student was not found, add a new student
|
|
if (!found) {
|
|
strcpy(students[size].name, name);
|
|
students[size].votes = votes;
|
|
size++;
|
|
}
|
|
}
|
|
|
|
// sort students based on their votes
|
|
qsort(students, size, sizeof(struct student), compare);
|
|
|
|
// print the results
|
|
printf("Vysledky:\n");
|
|
for (int i = 0; i < size; i++) {
|
|
printf("%d %s\n", students[i].votes, students[i].name);
|
|
}
|
|
|
|
return 0;
|
|
}
|