pvjc24/cv10/program.c
2024-04-25 20:28:01 +02:00

63 lines
1.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function to compare strings for qsort
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
int max_students;
char **applications = NULL;
char buffer[100];
int num_applications = 0;
// Read the maximum number of students to accept
if (scanf("%d", &max_students) != 1 || max_students <= 0) {
puts("Nespravny vstup");
return 1;
}
// Allocate memory for the list of applications
applications = (char **)malloc(max_students * sizeof(char *));
if (applications == NULL) {
puts("Chyba alokacie pamate");
return 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");
return 1;
}
num_applications++;
}
// Check if any applications were read
if (num_applications == 0) {
puts("Ziadne prihlasky");
return 1;
}
// Sort the applications alphabetically
qsort(applications, num_applications, sizeof(char *), compare);
// Print the accepted students
puts("Prijati studenti:");
for (int i = 0; i < num_applications; i++) {
printf("%s\n", applications[i]);
free(applications[i]); // Free memory for each application
}
free(applications); // Free the array of applications
return 0;
}