Initialization

This commit is contained in:
Kozar 2024-04-25 20:28:01 +02:00
parent 52ce942162
commit c5a533ebc2

View File

@ -2,7 +2,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
// Funkcia na kontrolu abecedného poradia // Function to compare strings for qsort
int compare(const void *a, const void *b) { int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b); return strcmp(*(const char **)a, *(const char **)b);
} }
@ -13,21 +13,25 @@ int main() {
char buffer[100]; char buffer[100];
int num_applications = 0; 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) { if (scanf("%d", &max_students) != 1 || max_students <= 0) {
puts("Nespravny vstup"); puts("Nespravny vstup");
return 1; 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 *)); applications = (char **)malloc(max_students * sizeof(char *));
if (applications == NULL) { if (applications == NULL) {
puts("Chyba alokacie pamate"); puts("Chyba alokacie pamate");
return 1; return 1;
} }
// Načítanie prihlášok // Read the applications
while (num_applications < max_students && scanf("%s", buffer) == 1) { 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); applications[num_applications] = strdup(buffer);
if (applications[num_applications] == NULL) { if (applications[num_applications] == NULL) {
puts("Chyba alokacie pamate"); puts("Chyba alokacie pamate");
@ -36,27 +40,23 @@ int main() {
num_applications++; num_applications++;
} }
// Kontrola, či boli načítané nejaké prihlášky // Check if any applications were read
if (num_applications == 0) { if (num_applications == 0) {
puts("Ziadne prihlasky"); puts("Ziadne prihlasky");
return 1; return 1;
} }
// Usporiadanie prihlášok podľa abecedy // Sort the applications alphabetically
qsort(applications, num_applications, sizeof(char *), compare); qsort(applications, num_applications, sizeof(char *), compare);
// Výpis prijatých študentov // Print the accepted students
puts("Prijati studenti:"); puts("Prijati studenti:");
int i; for (int i = 0; i < num_applications; i++) {
for (i = 0; i < num_applications; i++) {
printf("%s\n", applications[i]); printf("%s\n", applications[i]);
free(applications[i]); // Free memory for each application
} }
// Uvoľnenie pamäte free(applications); // Free the array of applications
for (i = 0; i < num_applications; i++) {
free(applications[i]);
}
free(applications);
return 0; return 0;
} }