pvjc24/cv10/program.c
2024-04-18 12:40:23 +00:00

90 lines
2.0 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 100
int compare(const void *a, const void *b) {
const char *name1 = *(const char **)a;
const char *name2 = *(const char **)b;
return strcmp(name1, name2);
}
int main() {
int maxStudents;
char name[MAX_NAME_LENGTH];
char **names = NULL;
int count = 0;
int capacity = 0;
if (scanf("%d\n", &maxStudents) != 1 || maxStudents <= 0) {
puts("Nespravny vstup");
return 0;
}
while (fgets(name, MAX_NAME_LENGTH, stdin)) {
if (name[0] == '\n') break;
name[strcspn(name, "\n")] = '\0';
if (count >= capacity) {
capacity = capacity == 0 ? 4 : capacity * 2;
names = realloc(names, capacity * sizeof(char *));
if (names == NULL) {
perror("Failed to reallocate memory");
return 0;
}
}
int isDuplicate = 0;
for (int i = 0; i < count; i++) {
if (strcmp(names[i], name) == 0) {
isDuplicate = 1;
break;
}
}
if (!isDuplicate) {
names[count] = strdup(name);
if (names[count] == NULL) {
perror("Failed to duplicate name");
return 0;
}
count++;
}
}
if (count == 0) {
puts("Ziadne prihlasky");
return 0;
}
qsort(names, count, sizeof(char *), compare);
puts("Prijati studenti:");
int limit = count < maxStudents ? count : maxStudents;
for (int i = 0; i < limit; i++) {
puts(names[i]);
}
if (count > maxStudents) {
puts("Neprijati studenti:");
for (int i = maxStudents; i < count; i++) {
puts(names[i]);
}
}
for (int i = 0; i < count; i++) {
free(names[i]);
}
free(names);
return 0;
}