Initialization

This commit is contained in:
Kozar 2024-04-25 20:28:58 +02:00
parent c5a533ebc2
commit 6083688b7e

View File

@ -2,61 +2,71 @@
#include <stdlib.h>
#include <string.h>
// Function to compare strings for qsort
int compare(const void *a, const void *b) {
int compare_names(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
int max_students;
char **applications = NULL;
int count;
char buffer[100];
int num_applications = 0;
char **applications;
int i, j;
// Read the maximum number of students to accept
if (scanf("%d", &max_students) != 1 || max_students <= 0) {
puts("Nespravny vstup");
if (scanf("%d", &count) != 1 || count <= 0) {
printf("Nespravny vstup\n");
return 1;
}
// Allocate memory for the list of applications
applications = (char **)malloc(max_students * sizeof(char *));
if (applications == NULL) {
puts("Chyba alokacie pamate");
applications = (char **)malloc(count * sizeof(char *));
if (!applications) {
printf("Chyba pri alokacii pamate\n");
return 1;
}
// Read the applications
while (num_applications < max_students && fgets(buffer, sizeof(buffer), stdin) != NULL && buffer[0] != '\n') {
size_t len = strlen(buffer);
if (buffer[len - 1] == '\n') {
buffer[len - 1] = '\0'; // Remove the newline character
i = 0;
while (i < count && fgets(buffer, sizeof(buffer), stdin)) {
int len = strlen(buffer);
if (len > 0 && buffer[len - 1] == '\n') { // Remove newline character if present
buffer[len - 1] = '\0';
}
applications[num_applications] = strdup(buffer);
if (applications[num_applications] == NULL) {
puts("Chyba alokacie pamate");
return 1;
int found = 0;
for (j = 0; j < i; j++) {
if (strcmp(applications[j], buffer) == 0) {
found = 1;
break;
}
}
if (!found) {
applications[i] = strdup(buffer);
i++;
}
num_applications++;
}
// Check if any applications were read
if (num_applications == 0) {
puts("Ziadne prihlasky");
if (i == 0) {
printf("Ziadne prihlasky\n");
return 1;
}
// Sort the applications alphabetically
qsort(applications, num_applications, sizeof(char *), compare);
qsort(applications, i, sizeof(char *), compare_names);
// Print the accepted students
puts("Prijati studenti:");
for (int i = 0; i < num_applications; i++) {
printf("%s\n", applications[i]);
free(applications[i]); // Free memory for each application
printf("Prijati studenti:");
for (j = 0; j < i; j++) {
printf("%s\n", applications[j]);
}
free(applications); // Free the array of applications
if (count < i) {
printf("Neprijati studenti:");
for (; j < i; j++) {
printf("%s\n", applications[j]);
}
}
// Free allocated memory
for (j = 0; j < i; j++) {
free(applications[j]);
}
free(applications);
return 0;
}