pvjc24/cv10/program.c
2024-04-23 10:10:22 +02:00

87 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 100
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
void free_memory(char **array, int length) {
for (int i = 0; i < length; i++) {
free(array[i]);
}
free(array);
}
int main() {
int max_students;
char name[MAX_NAME_LENGTH];
char **students = NULL;
int num_students = 0;
if (scanf("%d\n", &max_students) != 1 || max_students <= 0) {
puts("Nespravny vstup");
return 1;
}
students = (char **)malloc(max_students * sizeof(char *));
if (students == NULL) {
puts("Memory allocation failed");
return 1;
}
while (fgets(name, MAX_NAME_LENGTH, stdin) && num_students < max_students) {
name[strcspn(name, "\n")] = 0;
if (strlen(name) == 0) {
break;
}
int duplicate = 0;
for (int i = 0; i < num_students; i++) {
if (strcmp(students[i], name) == 0) {
duplicate = 1;
break;
}
}
if (!duplicate) {
students[num_students] = strdup(name);
if (students[num_students] == NULL) {
puts("Memory allocation failed");
free_memory(students, num_students);
return 1;
}
num_students++;
}
}
if (num_students == 0) {
puts("Ziadne prihlasky");
free(students);
return 1;
}
qsort(students, num_students, sizeof(char *), compare);
puts("Prijati studenti:");
for (int i = 0; i < num_students; i++) {
if (i < max_students) {
puts(students[i]);
} else {
if (i == max_students) {
puts("Neprijati studenti:");
}
puts(students[i]);
}
}
free_memory(students, num_students);
return 0;
}