pvjc24/cv10/program.c
2024-04-19 15:39:33 +02:00

88 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 max_students;
char name[MAX_NAME_LENGTH];
char **names = NULL;
int size = 0, capacity = 10;
names = (char **)malloc(capacity * sizeof(char *));
if (names == NULL) {
puts("Memory allocation error");
return 1;
}
if (scanf("%d\n", &max_students) != 1 || max_students <= 0) {
puts("Nespravny vstup");
free(names);
return 1;
}
while (fgets(name, MAX_NAME_LENGTH, stdin) != NULL) {
if (name[0] == '\n') break;
name[strcspn(name, "\n")] = 0;
int duplicate = 0;
for (int i = 0; i < size; i++) {
if (strcmp(names[i], name) == 0) {
duplicate = 1;
break;
}
}
if (duplicate) continue;
if (size == capacity) {
capacity *= 2;
names = (char **)realloc(names, capacity * sizeof(char *));
if (names == NULL) {
puts("Memory allocation error");
return 1;
}
}
names[size] = strdup(name);
if (names[size] == NULL) {
puts("Memory allocation error");
return 1;
}
size++;
}
if (size == 0) {
puts("Ziadne prihlasky");
free(names);
return 1;
}
qsort(names, size, sizeof(char *), compare);
puts("Prijati studenti:");
int accepted = size < max_students ? size : max_students;
for (int i = 0; i < accepted; i++) {
puts(names[i]);
}
if (size > max_students) {
puts("Neprijati studenti:");
for (int i = max_students; i < size; i++) {
puts(names[i]);
}
}
for (int i = 0; i < size; i++) {
free(names[i]);
}
free(names);
return 0;
}