pvjc24/cv10/program.c

63 lines
1.7 KiB
C
Raw Normal View History

2024-04-22 12:01:17 +00:00
#include <stdio.h>
2024-04-25 16:32:35 +00:00
#include <stdlib.h>
2024-04-25 15:29:10 +00:00
#include <string.h>
2024-04-22 12:01:17 +00:00
2024-04-25 18:28:01 +00:00
// Function to compare strings for qsort
2024-04-25 18:10:32 +00:00
int compare(const void *a, const void *b) {
2024-04-25 17:04:21 +00:00
return strcmp(*(const char **)a, *(const char **)b);
}
2024-04-22 12:01:17 +00:00
int main() {
2024-04-25 18:10:32 +00:00
int max_students;
char **applications = NULL;
2024-04-25 16:42:45 +00:00
char buffer[100];
2024-04-25 18:10:32 +00:00
int num_applications = 0;
2024-04-22 12:06:40 +00:00
2024-04-25 18:28:01 +00:00
// Read the maximum number of students to accept
2024-04-25 18:10:32 +00:00
if (scanf("%d", &max_students) != 1 || max_students <= 0) {
puts("Nespravny vstup");
2024-04-22 12:06:40 +00:00
return 1;
}
2024-04-22 12:01:17 +00:00
2024-04-25 18:28:01 +00:00
// Allocate memory for the list of applications
2024-04-25 18:10:32 +00:00
applications = (char **)malloc(max_students * sizeof(char *));
if (applications == NULL) {
puts("Chyba alokacie pamate");
2024-04-25 16:42:45 +00:00
return 1;
2024-04-25 16:32:35 +00:00
}
2024-04-25 15:41:03 +00:00
2024-04-25 18:28:01 +00:00
// 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
}
2024-04-25 18:10:32 +00:00
applications[num_applications] = strdup(buffer);
if (applications[num_applications] == NULL) {
puts("Chyba alokacie pamate");
return 1;
2024-04-25 16:42:45 +00:00
}
2024-04-25 18:10:32 +00:00
num_applications++;
2024-04-25 16:42:45 +00:00
}
2024-04-25 18:28:01 +00:00
// Check if any applications were read
2024-04-25 18:10:32 +00:00
if (num_applications == 0) {
puts("Ziadne prihlasky");
2024-04-25 16:32:35 +00:00
return 1;
}
2024-04-25 15:56:47 +00:00
2024-04-25 18:28:01 +00:00
// Sort the applications alphabetically
2024-04-25 18:10:32 +00:00
qsort(applications, num_applications, sizeof(char *), compare);
2024-04-22 12:01:17 +00:00
2024-04-25 18:28:01 +00:00
// Print the accepted students
2024-04-25 18:10:32 +00:00
puts("Prijati studenti:");
2024-04-25 18:28:01 +00:00
for (int i = 0; i < num_applications; i++) {
2024-04-25 18:10:32 +00:00
printf("%s\n", applications[i]);
2024-04-25 18:28:01 +00:00
free(applications[i]); // Free memory for each application
2024-04-22 12:01:17 +00:00
}
2024-04-25 18:28:01 +00:00
free(applications); // Free the array of applications
2024-04-25 16:42:45 +00:00
2024-04-22 12:01:17 +00:00
return 0;
2024-04-25 18:02:38 +00:00
}