funguje
This commit is contained in:
parent
1ee7eeaa4d
commit
69cac7b871
79
cv5/program.c
Normal file
79
cv5/program.c
Normal file
@ -0,0 +1,79 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_STUDENTS 100
|
||||
#define MAX_NAME_LENGTH 50
|
||||
|
||||
struct Student {
|
||||
char name[MAX_NAME_LENGTH];
|
||||
int votes;
|
||||
};
|
||||
|
||||
// Funkcia načíta študentov zo štandardného vstupu a sčíta ich hlasy
|
||||
int read_and_sum_votes(struct Student students[], int max_students) {
|
||||
int count = 0;
|
||||
while (count < max_students) {
|
||||
int votes;
|
||||
char name[MAX_NAME_LENGTH];
|
||||
if (scanf("%d %[^\n]", &votes, name) != 2) {
|
||||
break; // Koniec vstupu alebo chyba
|
||||
}
|
||||
|
||||
// Hľadáme, či už sme tento študent videli
|
||||
int found = 0;
|
||||
for (int i = 0; i < count; i++) {
|
||||
if (strcmp(students[i].name, name) == 0) {
|
||||
// Ak sme študenta našli, pridáme mu hlasy
|
||||
students[i].votes += votes;
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Ak sme študenta ešte nevideli, pridáme ho do zoznamu
|
||||
if (!found) {
|
||||
strcpy(students[count].name, name);
|
||||
students[count].votes = votes;
|
||||
count++;
|
||||
}
|
||||
|
||||
// Zbavíme sa koncového znaku nového riadku z bufferu vstupu
|
||||
getchar();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Funkcia na porovnávanie študentov pre qsort
|
||||
int compare(const void *p1, const void *p2) {
|
||||
const struct Student *s1 = (const struct Student *)p1;
|
||||
const struct Student *s2 = (const struct Student *)p2;
|
||||
// Porovnanie podľa počtu hlasov, v prípade rovnakého počtu podľa mena
|
||||
if (s1->votes != s2->votes) {
|
||||
return s2->votes - s1->votes;
|
||||
} else {
|
||||
return strcmp(s1->name, s2->name);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
struct Student students[MAX_STUDENTS];
|
||||
int count = read_and_sum_votes(students, MAX_STUDENTS);
|
||||
|
||||
if (count == 0) {
|
||||
printf("Nepodarilo nacitat nic\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Triedenie študentov
|
||||
qsort(students, count, sizeof(struct Student), compare);
|
||||
|
||||
// Výpis výsledkov
|
||||
printf("Vysledky:\n");
|
||||
for (int i = 0; i < count; i++) {
|
||||
printf("%d %s\n", students[i].votes, students[i].name);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user