pvjc24/cv5/program.c

89 lines
2.2 KiB
C
Raw Normal View History

2024-03-21 12:38:59 +00:00
#include <stdio.h>
2024-03-21 15:43:03 +00:00
#include <stdlib.h>
#include <string.h>
2024-03-21 12:38:59 +00:00
2024-03-21 13:09:15 +00:00
#define SIZE 100
struct student {
char name[SIZE];
int votes;
};
2024-03-21 15:43:03 +00:00
2024-03-21 15:48:25 +00:00
// comparison function for sorting students
2024-03-21 15:43:03 +00:00
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 {
2024-03-21 16:18:00 +00:00
// if votes are the same, compare names
2024-03-21 15:43:03 +00:00
return strcmp(student_a->name, student_b->name);
}
}
int main() {
struct student students[SIZE];
int size = 0;
2024-03-21 16:34:39 +00:00
int successful_lines = 0; // Counter for successful lines read
2024-03-21 15:43:03 +00:00
2024-03-21 15:48:25 +00:00
// read student data from standard input
2024-03-21 15:43:03 +00:00
while (1) {
char line[SIZE];
memset(line, 0, SIZE);
char *r = fgets(line, SIZE, stdin);
2024-03-21 16:18:39 +00:00
// check if the line is empty
2024-03-21 15:45:29 +00:00
if (r == NULL || (r[0] == '\n' && strlen(r) == 1)) {
2024-03-21 16:18:39 +00:00
// end of input
2024-03-21 15:43:03 +00:00
break;
}
2024-03-21 15:48:25 +00:00
// parse the string and extract number of votes and student name
2024-03-21 15:43:03 +00:00
int votes;
2024-03-21 15:51:55 +00:00
char name[SIZE];
2024-03-21 16:18:39 +00:00
if (sscanf(line, "%d %[^\n]", &votes, name) != 2) {
2024-03-21 16:34:39 +00:00
if (successful_lines >= 1){
2024-03-21 16:37:37 +00:00
break;
2024-03-21 16:34:39 +00:00
}
else{
2024-03-21 16:36:50 +00:00
printf("Nepodarilo nacitat nic\n");
break;
2024-03-21 16:34:39 +00:00
}
2024-03-21 15:43:03 +00:00
}
2024-03-21 15:51:55 +00:00
2024-03-21 16:34:39 +00:00
successful_lines++;
2024-03-21 15:51:55 +00:00
// check if this student already exists
2024-03-21 16:03:04 +00:00
int found = 0;
2024-03-21 15:51:55 +00:00
for (int i = 0; i < size; i++) {
if (strcmp(students[i].name, name) == 0) {
// add votes to existing student
students[i].votes += votes;
2024-03-21 16:03:04 +00:00
found = 1;
2024-03-21 15:51:55 +00:00
break;
}
}
// if the student was not found, add a new student
if (!found) {
strcpy(students[size].name, name);
students[size].votes = votes;
size++;
}
2024-03-21 15:43:03 +00:00
}
2024-03-21 15:48:25 +00:00
// sort students based on their votes
2024-03-21 15:43:03 +00:00
qsort(students, size, sizeof(struct student), compare);
2024-03-21 15:48:25 +00:00
// print the results
2024-03-21 15:57:37 +00:00
printf("Vysledky:\n");
2024-03-21 15:43:03 +00:00
for (int i = 0; i < size; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
}
return 0;
2024-03-21 16:34:39 +00:00
}