pvjc24/cv10/program.c

91 lines
2.0 KiB
C
Raw Normal View History

2024-04-18 12:35:06 +00:00
#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 1;
}
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 1;
}
}
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 1;
}
count++;
}
}
if (count == 0) {
puts("Ziadne prihlasky");
return 1;
}
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;
}