pvjc24/cv10/program.c

80 lines
1.8 KiB
C
Raw Normal View History

2024-04-23 07:41:48 +00:00
#include <stdio.h>
2024-04-17 21:09:04 +00:00
#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) {
2024-04-23 07:41:48 +00:00
return strcmp(*(const char **)a, *(const char **)b);
2024-04-17 21:09:04 +00:00
}
2024-04-23 08:10:22 +00:00
void free_memory(char **array, int length) {
for (int i = 0; i < length; i++) {
free(array[i]);
}
free(array);
}
2024-04-17 21:09:04 +00:00
int main() {
2024-04-19 13:39:33 +00:00
int max_students;
2024-04-23 08:10:22 +00:00
char name[MAX_NAME_LENGTH];
char **students = NULL;
int num_students = 0;
2024-04-23 07:41:48 +00:00
2024-04-23 08:10:22 +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-23 07:41:48 +00:00
return 1;
2024-04-17 21:09:04 +00:00
}
2024-04-23 08:10:22 +00:00
students = (char **)malloc(max_students * sizeof(char *));
2024-04-23 07:41:48 +00:00
if (students == NULL) {
puts("Memory allocation failed");
return 1;
}
2024-04-23 08:10:22 +00:00
2024-04-23 09:05:21 +00:00
while (fgets(name, MAX_NAME_LENGTH, stdin)) {
2024-04-23 08:10:22 +00:00
name[strcspn(name, "\n")] = 0;
if (strlen(name) == 0) {
break;
}
int duplicate = 0;
for (int i = 0; i < num_students; i++) {
if (strcmp(students[i], name) == 0) {
duplicate = 1;
2024-04-19 13:39:33 +00:00
break;
}
}
2024-04-23 08:10:22 +00:00
if (!duplicate) {
2024-04-23 09:05:21 +00:00
if (num_students < max_students) {
students[num_students] = strdup(name);
if (students[num_students] == NULL) {
puts("Memory allocation failed");
free_memory(students, num_students);
return 1;
}
num_students++;
2024-04-23 07:41:48 +00:00
}
2024-04-17 21:09:04 +00:00
}
}
2024-04-23 08:10:22 +00:00
if (num_students == 0) {
2024-04-17 21:09:04 +00:00
puts("Ziadne prihlasky");
2024-04-23 07:41:48 +00:00
free(students);
return 1;
2024-04-17 21:09:04 +00:00
}
2024-04-23 08:10:22 +00:00
qsort(students, num_students, sizeof(char *), compare);
2024-04-17 21:09:04 +00:00
puts("Prijati studenti:");
2024-04-23 08:10:22 +00:00
for (int i = 0; i < num_students; i++) {
2024-04-23 09:05:21 +00:00
puts(students[i]);
2024-04-17 21:09:04 +00:00
}
2024-04-23 08:10:22 +00:00
free_memory(students, num_students);
2024-04-17 21:09:04 +00:00
return 0;
}