diff --git a/cv10/program.c b/cv10/program.c index 4a0d918..ac3c104 100644 --- a/cv10/program.c +++ b/cv10/program.c @@ -8,67 +8,79 @@ int compare(const void *a, const void *b) { return strcmp(*(const char **)a, *(const char **)b); } +void free_memory(char **array, int length) { + for (int i = 0; i < length; i++) { + free(array[i]); + } + free(array); +} + int main() { int max_students; - char temp[MAX_NAME_LENGTH]; - char **students; - int count = 0, unique_count = 0; + char name[MAX_NAME_LENGTH]; + char **students = NULL; + int num_students = 0; - if (scanf("%d", &max_students) != 1 || max_students <= 0) { + if (scanf("%d\n", &max_students) != 1 || max_students <= 0) { puts("Nespravny vstup"); return 1; } - - students = malloc(max_students * sizeof(char *)); + + students = (char **)malloc(max_students * sizeof(char *)); if (students == NULL) { puts("Memory allocation failed"); return 1; } - - while (scanf("%99s", temp) == 1) { - int is_unique = 1; - for (int i = 0; i < unique_count; i++) { - if (strcmp(students[i], temp) == 0) { - is_unique = 0; + + while (fgets(name, MAX_NAME_LENGTH, stdin) && num_students < max_students) { + 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; break; } } - - if (is_unique) { - students[unique_count] = strdup(temp); - if (students[unique_count] == NULL) { + + if (!duplicate) { + students[num_students] = strdup(name); + if (students[num_students] == NULL) { puts("Memory allocation failed"); - for (int i = 0; i < unique_count; i++) { - free(students[i]); - } - free(students); + free_memory(students, num_students); return 1; } - unique_count++; - if (unique_count >= max_students) { - break; - } + num_students++; } } - - if (unique_count == 0) { + + if (num_students == 0) { puts("Ziadne prihlasky"); free(students); return 1; } - - qsort(students, unique_count, sizeof(char *), compare); - + + qsort(students, num_students, sizeof(char *), compare); + puts("Prijati studenti:"); - for (int i = 0; i < unique_count; i++) { - puts(students[i]); + for (int i = 0; i < num_students; i++) { + if (i < max_students) { + puts(students[i]); + } else { + if (i == max_students) { + puts("Neprijati studenti:"); + } + puts(students[i]); + } } - - for (int i = 0; i < unique_count; i++) { - free(students[i]); - } - free(students); - + + free_memory(students, num_students); + return 0; }