From b968ad709149ae883b5b2c7116f38bf7448826e7 Mon Sep 17 00:00:00 2001 From: st529yr Date: Fri, 22 Mar 2024 00:06:32 +0100 Subject: [PATCH] funguje --- cv5/program.c | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/cv5/program.c b/cv5/program.c index 8a13dea..48a227b 100644 --- a/cv5/program.c +++ b/cv5/program.c @@ -15,13 +15,29 @@ int main() { Student* students = NULL; while (fgets(line, SIZE, stdin) != NULL) { - int hlasov; - char meno[SIZE]; - if (sscanf(line, "%d %99[^\n]", &hlasov, meno) != 2) { + char* endptr; + int hlasov = strtol(line, &endptr, 10); + if (endptr == line || *endptr != ' ' || hlasov < 0) { printf("CHYBA: Neplatny zapis na riadku.\n"); return 1; } - + 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) { + printf("CHYBA: Nepodarilo sa alokovať pamäť.\n"); + return 1; + } + + // 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) { @@ -29,13 +45,8 @@ int main() { return 1; } - // 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); + // Nastavenie hodnôt pre nového študenta + students[num_students].meno = meno; students[num_students].hlasov = hlasov; num_students++; @@ -56,3 +67,5 @@ int main() { return 0; } + +