#Anyone know why when this is ran and you
1 messages · Page 1 of 1 (latest)
while I know very little about whatever C this is, chatgpt makes sense:
The issue seems to be related to how you're reading input from the user using fgets. When you enter the student ID, the newline character (\n) is included in the input buffer. Later, when you try to read the course code, fgets considers the newline character as the complete input and doesn't wait for additional input from the user.
To fix this issue, you can add an extra getchar() after reading the student ID to consume the remaining newline character before reading the course code. Here's an updated version of your code with the necessary modifications:
void addStudent(int* student_id, int* course_code, Student* students, Course* courses) {
char id[MAX_ID];
char code[MAX_CODE];
printf("Enter Student ID: ");
fgets(id, MAX_ID, stdin);
id[strcspn(id, "\n")] = '\0';
// Consume remaining newline character
getchar();
int i, j;
for (i = 0; i < *student_id; i++) {
if (strcmp(students[i].id, id) == 0) {
break;
}
}
if (i == *student_id) {
printf("Student ID not found.\n");
return;
}
printf("Enter Course Code: ");
fgets(code, MAX_CODE, stdin);
code[strcspn(code, "\n")] = '\0';
for (j = 0; j < *course_code; j++) {
if (strcmp(courses[j].code, code) == 0) {
break;
}
}
if (j == *course_code) {
printf("Course Code not found.\n");
return;
}
printf("Student %s added to Course %s.\n", id, code);
}
With this modification, the program will correctly wait for input for the course code after entering the student ID.
@carmine hornet perhaps that helps, if you haven't already gotten it
tldr; i pasted your problem into chatgpt and that's what it told me