pvjc24/cv10/program.c

88 lines
2.0 KiB
C
Raw Normal View History

2024-04-17 21:09:04 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2024-04-19 13:39:33 +00:00
#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);
2024-04-17 21:09:04 +00:00
}
int main() {
2024-04-19 13:39:33 +00:00
int max_students;
char name[MAX_NAME_LENGTH];
2024-04-17 21:09:04 +00:00
char **names = NULL;
2024-04-19 13:39:33 +00:00
int size = 0, capacity = 10;
2024-04-17 21:09:04 +00:00
2024-04-19 13:39:33 +00:00
names = (char **)malloc(capacity * sizeof(char *));
if (names == NULL) {
puts("Memory allocation error");
return 1;
}
2024-04-17 21:09:04 +00:00
2024-04-19 13:39:33 +00:00
if (scanf("%d\n", &max_students) != 1 || max_students <= 0) {
2024-04-17 21:09:04 +00:00
puts("Nespravny vstup");
2024-04-19 13:39:33 +00:00
free(names);
2024-04-17 21:09:04 +00:00
return 1;
}
2024-04-19 13:39:33 +00:00
while (fgets(name, MAX_NAME_LENGTH, stdin) != NULL) {
if (name[0] == '\n') break;
name[strcspn(name, "\n")] = 0;
2024-04-17 21:09:04 +00:00
2024-04-19 13:39:33 +00:00
int duplicate = 0;
for (int i = 0; i < size; i++) {
if (strcmp(names[i], name) == 0) {
duplicate = 1;
break;
}
}
if (duplicate) continue;
2024-04-17 21:09:04 +00:00
2024-04-19 13:39:33 +00:00
if (size == capacity) {
capacity *= 2;
names = (char **)realloc(names, capacity * sizeof(char *));
if (names == NULL) {
puts("Memory allocation error");
2024-04-17 21:09:04 +00:00
return 1;
}
}
2024-04-19 13:39:33 +00:00
names[size] = strdup(name);
if (names[size] == NULL) {
puts("Memory allocation error");
2024-04-17 21:09:04 +00:00
return 1;
}
2024-04-19 13:39:33 +00:00
size++;
2024-04-17 21:09:04 +00:00
}
2024-04-19 13:39:33 +00:00
if (size == 0) {
2024-04-17 21:09:04 +00:00
puts("Ziadne prihlasky");
free(names);
return 1;
}
2024-04-19 13:39:33 +00:00
qsort(names, size, sizeof(char *), compare);
2024-04-17 21:09:04 +00:00
puts("Prijati studenti:");
2024-04-19 13:39:33 +00:00
int accepted = size < max_students ? size : max_students;
for (int i = 0; i < accepted; i++) {
2024-04-17 21:09:04 +00:00
puts(names[i]);
}
2024-04-19 13:39:33 +00:00
if (size > max_students) {
2024-04-17 21:09:04 +00:00
puts("Neprijati studenti:");
2024-04-19 13:39:33 +00:00
for (int i = max_students; i < size; i++) {
2024-04-17 21:09:04 +00:00
puts(names[i]);
}
}
2024-04-19 13:39:33 +00:00
for (int i = 0; i < size; i++) {
2024-04-17 21:09:04 +00:00
free(names[i]);
}
free(names);
return 0;
}