pvjc24/cv5/program.c

59 lines
1.4 KiB
C
Raw Normal View History

2024-03-21 22:47:06 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2024-03-21 23:01:55 +00:00
#define SIZE 100
2024-03-21 22:47:06 +00:00
2024-03-21 23:01:55 +00:00
typedef struct {
2024-03-21 23:04:41 +00:00
char* meno;
int hlasov;
2024-03-21 23:01:55 +00:00
} Student;
2024-03-21 22:47:06 +00:00
int main() {
2024-03-21 23:01:55 +00:00
char line[SIZE];
2024-03-21 23:04:41 +00:00
int num_students = 0;
Student* students = NULL;
2024-03-21 23:01:55 +00:00
2024-03-21 23:04:41 +00:00
while (fgets(line, SIZE, stdin) != NULL) {
int hlasov;
char meno[SIZE];
if (sscanf(line, "%d %99[^\n]", &hlasov, meno) != 2) {
2024-03-21 22:58:42 +00:00
printf("CHYBA: Neplatny zapis na riadku.\n");
2024-03-21 23:04:41 +00:00
return 1;
}
// Reallokácia pamäte pre ďalšieho študenta
students = realloc(students, (num_students + 1) * sizeof(Student));
if (students == NULL) {
printf("CHYBA: Nepodarilo sa alokovať pamäť.\n");
return 1;
2024-03-21 22:58:42 +00:00
}
2024-03-21 23:01:55 +00:00
2024-03-21 23:04:41 +00:00
// Alokácia pamäte pre meno študenta a kópia mena
students[num_students].meno = malloc(strlen(meno) + 1);
if (students[num_students].meno == NULL) {
printf("CHYBA: Nepodarilo sa alokovať pamäť.\n");
return 1;
}
strcpy(students[num_students].meno, meno);
students[num_students].hlasov = hlasov;
num_students++;
2024-03-21 22:47:06 +00:00
}
2024-03-21 23:01:55 +00:00
// Výpis výsledkov
2024-03-21 23:04:41 +00:00
printf("Vysledky:\n");
for (int i = 0; i < num_students; i++) {
printf("%d %s\n", students[i].hlasov, students[i].meno);
}
// Uvoľnenie pamäte
for (int i = 0; i < num_students; i++) {
free(students[i].meno);
2024-03-21 22:58:42 +00:00
}
2024-03-21 23:04:41 +00:00
free(students);
2024-03-21 23:01:55 +00:00
2024-03-21 22:47:06 +00:00
return 0;
}