pvjc24/cv10/program.c
2024-04-19 15:48:31 +02:00

95 lines
2.2 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 0;
}
if (scanf("%d\n", &max_students) != 1 || max_students <= 0) {
puts("Nespravny vstup");
free(names);
return 0;
}
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;
char **new_names = (char **)realloc(names, capacity * sizeof(char *));
if (new_names == NULL) {
puts("Memory allocation error");
for (int j = 0; j < size; j++) free(names[j]);
free(names);
return 0;
}
names = new_names;
}
names[size] = strdup(name);
if (names[size] == NULL) {
puts("Memory allocation error");
for (int j = 0; j < size; j++) free(names[j]);
free(names);
return 0;
}
size++;
}
if (size == 0) {
puts("Ziadne prihlasky");
free(names);
return 0;
}
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;
}