pvjc24/cv5/program.c

72 lines
1.7 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) {
2024-03-21 23:06:32 +00:00
char* endptr;
int hlasov = strtol(line, &endptr, 10);
if (endptr == line || *endptr != ' ' || hlasov < 0) {
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;
}
2024-03-21 23:06:32 +00:00
endptr++; // Preskočenie medzery
// Preskočenie medzier za počtom hlasov
while (*endptr == ' ') {
endptr++;
}
// Alokácia pamäte pre meno študenta
char* meno = malloc(strlen(endptr) + 1);
if (meno == NULL) {
2024-03-21 23:04:41 +00:00
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:06:32 +00:00
// Kopírovanie mena
strcpy(meno, endptr);
// Reallokácia pamäte pre ďalšieho študenta
students = realloc(students, (num_students + 1) * sizeof(Student));
if (students == NULL) {
2024-03-21 23:04:41 +00:00
printf("CHYBA: Nepodarilo sa alokovať pamäť.\n");
return 1;
}
2024-03-21 23:06:32 +00:00
// Nastavenie hodnôt pre nového študenta
students[num_students].meno = meno;
2024-03-21 23:04:41 +00:00
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;
}
2024-03-21 23:06:32 +00:00