I’m working on a C program that lets users input courses. Right now it just asks for the input but doesn’t save it. I want to store the courses in the struct Students like this:
struct Students {
// other fields
char courses[NUM_COURSES][100];
// more fields
};
After saving, I should be able to print the courses like this:
printf("Courses: %s\n", temp->courses);
My code already has the input part working. It uses a do-while loop to get courses from the user. How can I modify it to save these courses in the struct? Also, any tips on making the code more efficient would be great. Thanks!
Hey Luke87! I’ve been working on something similar recently. Have you thought about using a dynamic approach instead of a fixed-size array? It could give you more flexibility.
For your current setup though, you’re on the right track. You just need to tweak your loop a bit to save each course. Something like this might work:
int i = 0;
do {
// your existing input code here
if (i < NUM_COURSES) {
strcpy(temp.courses[i], input);
i++;
} else {
printf("Max courses reached!");
break;
}
} while (strcmp(input, "done") != 0);
This way, you’re saving each course as you go. Just remember to initialize your struct first!
For printing, you might want to loop through the courses instead of trying to print them all at once. The courses array is 2D, so you can’t just print it directly.
How many courses are you planning to handle? If it’s a lot, we might need to think about memory management. What do you think?
This saves each course as you go. Just remember to initialize courseCount to 0 first.
For printing, you’ll want to loop through the courses:
for (int i = 0; i < courseCount; i++) {
printf("Course %d: %s\n", i+1, temp.courses[i]);
}
This approach is pretty efficient, but if you’re dealing with a lot of courses, you might want to look into dynamic memory allocation. It’s a bit more complex but gives you more flexibility. Let me know if you need more help!
yo Luke, i’ve got a quick fix for ya. in ur loop, just add this:
if (courseCount < NUM_COURSES) {
strcpy(temp.courses[courseCount], inputCourse);
courseCount++;
}
this’ll save each course as u go. just make sure to initialize courseCount to 0 first. for printing, loop thru the courses instead of trying to print all at once. hope this helps!