I’m working on a C program that lets users input courses. Right now, it just asks for the input, but I want to store these courses in the struct Students array char courses[NUM_COURSES][100].
Here’s what I’m trying to do:
Get course input from the user
Save each course to the courses array in the struct
Be able to print the courses later using printf("Courses %s\n", temp->courses);
My current code has a struct Students with various fields like name, age, and courses. It also has functions to enter student info and search by name. The main function lets users pick courses from a list.
I’m stuck on how to properly save the selected courses into the struct array. Any ideas on how to modify the code to achieve this? Thanks for your help!
Ooh, storing user input in structs can be tricky, right? I totally get where you’re stuck! Have you thought about using a counter to keep track of how many courses are actually added? That way you don’t need to fill all NUM_COURSES slots if the user doesn’t want to.
Something like this might work:
int course_count = 0;
char course_input[100];
while (course_count < NUM_COURSES) {
printf("Enter a course (or 'done' to finish): ");
fgets(course_input, sizeof(course_input), stdin);
course_input[strcspn(course_input, "\n")] = 0; // Remove newline
if (strcmp(course_input, "done") == 0) break;
strcpy(temp->courses[course_count], course_input);
course_count++;
}
temp->num_courses = course_count; // Store the actual number of courses
This lets the user add courses until they’re done or hit the limit. Cool, huh?
For printing, you could do:
for (int i = 0; i < temp->num_courses; i++) {
printf("Course %d: %s\n", i+1, temp->courses[i]);
}
What do you think? Would this work for your program? Let me know if you need any clarification!