“program”

This commit is contained in:
Vasylenko 2024-04-23 11:22:59 +02:00
parent a5ea74f79c
commit b57c6d5ce9

View File

@ -21,12 +21,14 @@ int main() {
char **students = NULL; char **students = NULL;
int num_students = 0; int num_students = 0;
printf("Enter the maximum number of students that can be accepted: "); printf("Enter the maximum number of students that can be accepted: ");
if (scanf("%d\n", &max_students) != 1 || max_students <= 0) { if (scanf("%d\n", &max_students) != 1 || max_students <= 0) {
puts("Invalid input for the number of students."); puts("Invalid input for the number of students.");
return 1; return 1;
} }
students = (char **)malloc(max_students * sizeof(char *)); students = (char **)malloc(max_students * sizeof(char *));
if (students == NULL) { if (students == NULL) {
puts("Memory allocation failed."); puts("Memory allocation failed.");
@ -34,28 +36,29 @@ int main() {
} }
printf("Enter student names (press Enter twice to stop):\n"); printf("Enter student names (press Enter twice to stop):\n");
while (fgets(name, MAX_NAME_LENGTH, stdin)) { while (fgets(name, MAX_NAME_LENGTH, stdin) && num_students < max_students) {
if (name[strcspn(name, "\n")] = '\0', !*name) name[strcspn(name, "\n")] = '\0';
if (strlen(name) == 0) {
break; break;
}
int is_duplicate = 0;
int duplicate = 0;
for (int i = 0; i < num_students; i++) { for (int i = 0; i < num_students; i++) {
if (strcmp(students[i], name) == 0) { if (strcmp(students[i], name) == 0) {
is_duplicate = 1; duplicate = 1;
break; break;
} }
} }
if (!is_duplicate) { if (!duplicate) {
if (num_students < max_students) { students[num_students] = strdup(name);
students[num_students] = strdup(name); if (students[num_students] == NULL) {
if (students[num_students] == NULL) { puts("Memory allocation failed.");
puts("Memory allocation failed."); free_memory(students, num_students);
free_memory(students, num_students); return 1;
return 1;
}
num_students++;
} }
num_students++;
} }
} }
@ -65,15 +68,14 @@ int main() {
return 1; return 1;
} }
qsort(students, num_students, sizeof(char *), compare); qsort(students, num_students, sizeof(char *), compare);
puts("Accepted students:"); puts("Accepted students:");
for (int i = 0; i < num_students; i++) { for (int i = 0; i < num_students; i++) {
puts(students[i]); puts(students[i]);
} }
free_memory(students, num_students); free_memory(students, num_students);
return 0; return 0;
} }