From c5a533ebc255d7873cd9a97044b5a5a197d55aac Mon Sep 17 00:00:00 2001 From: ak643du Date: Thu, 25 Apr 2024 20:28:01 +0200 Subject: [PATCH] Initialization --- cv10/program.c | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/cv10/program.c b/cv10/program.c index 5b28683..e8c07d7 100644 --- a/cv10/program.c +++ b/cv10/program.c @@ -2,7 +2,7 @@ #include #include -// Funkcia na kontrolu abecedného poradia +// Function to compare strings for qsort int compare(const void *a, const void *b) { return strcmp(*(const char **)a, *(const char **)b); } @@ -13,21 +13,25 @@ int main() { char buffer[100]; int num_applications = 0; - // Načítanie počtu študentov na prijatie + // Read the maximum number of students to accept if (scanf("%d", &max_students) != 1 || max_students <= 0) { puts("Nespravny vstup"); return 1; } - // Dynamická alokácia pamäte pre zoznam prihlášok + // Allocate memory for the list of applications applications = (char **)malloc(max_students * sizeof(char *)); if (applications == NULL) { puts("Chyba alokacie pamate"); return 1; } - // Načítanie prihlášok - while (num_applications < max_students && scanf("%s", buffer) == 1) { + // Read the applications + while (num_applications < max_students && fgets(buffer, sizeof(buffer), stdin) != NULL && buffer[0] != '\n') { + size_t len = strlen(buffer); + if (buffer[len - 1] == '\n') { + buffer[len - 1] = '\0'; // Remove the newline character + } applications[num_applications] = strdup(buffer); if (applications[num_applications] == NULL) { puts("Chyba alokacie pamate"); @@ -36,27 +40,23 @@ int main() { num_applications++; } - // Kontrola, či boli načítané nejaké prihlášky + // Check if any applications were read if (num_applications == 0) { puts("Ziadne prihlasky"); return 1; } - // Usporiadanie prihlášok podľa abecedy + // Sort the applications alphabetically qsort(applications, num_applications, sizeof(char *), compare); - // Výpis prijatých študentov + // Print the accepted students puts("Prijati studenti:"); - int i; - for (i = 0; i < num_applications; i++) { + for (int i = 0; i < num_applications; i++) { printf("%s\n", applications[i]); + free(applications[i]); // Free memory for each application } - // Uvoľnenie pamäte - for (i = 0; i < num_applications; i++) { - free(applications[i]); - } - free(applications); + free(applications); // Free the array of applications return 0; }