Hey everyone! I’m working on a C program that deals with student data. Right now, it asks users to input courses, but I need help storing these courses in the struct Students
array. Specifically, I want to save them in char courses[NUM_COURSES][100]
.
I’m trying to make it so I can print the courses later using something like printf("Courses %s\n", temp->courses)
. Here’s a simplified version of what I’m working with:
#define NUM_COURSES 5
struct Students {
// other fields...
char courses[NUM_COURSES][100];
int num_selected_courses;
};
void add_course(struct Students *student, const char *course) {
if (student->num_selected_courses < NUM_COURSES) {
strcpy(student->courses[student->num_selected_courses], course);
student->num_selected_courses++;
}
}
int main() {
struct Students student = {0};
char course[100];
while (student.num_selected_courses < NUM_COURSES) {
printf("Enter course name: ");
scanf("%99s", course);
add_course(&student, course);
// Ask if user wants to add more courses
}
// Print courses
for (int i = 0; i < student.num_selected_courses; i++) {
printf("Course %d: %s\n", i + 1, student.courses[i]);
}
}
Any ideas on how to improve this? Thanks!
hey, your code’s solid! try using fgets() over scanf() for course names, and let user exit early by adding an exit option. it may help avoid input issues.
Your approach is on the right track. One suggestion to enhance your code would be to implement input validation. Check if the course name is empty or if it’s already in the list before adding it. This prevents duplicates and ensures meaningful entries.
Also, consider using dynamic memory allocation with malloc() for the courses array. This allows for flexibility in the number of courses a student can take, rather than being limited to a fixed number. Remember to free the allocated memory when you’re done.
Lastly, you might want to add a function to remove courses. This gives users the ability to correct mistakes or update their course list as needed. These improvements will make your program more robust and user-friendly.
Hey there, LeoNinja22! Your code’s looking pretty good already. 
I’m curious though, have you thought about how you’d handle courses with spaces in their names? Like “Introduction to Programming” or “Data Structures and Algorithms”?
Maybe we could tweak your input method a bit. What if we used fgets() instead of scanf()? It might look something like this:
fgets(course, sizeof(course), stdin);
course[strcspn(course, "\n")] = 0; // Remove newline
This way, you can capture full course names with spaces.
Also, I’m wondering… what happens if a student wants to stop entering courses before they hit the limit? Maybe we could add a way for them to finish early? Like, they could type ‘done’ or something when they’re finished?
What do you think about these ideas? Have you run into any other challenges with your program that you’d like to chat about?