I am working on a simple program in C that asks the user to give an input in a loop until they enter the letter Q when prompted. When I run the program however, it immediately skips the prompt to enter a character and asks the user to enter another input. Any idea why this happens and how I can fix it?
Here is my code:
while (exit != 'q' && exit != 'Q') {
printf("Please enter the grade for assignment #%d: ", assignmentNumber);
scanf("%lf", &gradeInput);
printf("Press q to quit, press any other character to continue: ");
exit = getchar();
}
I tried changing the getchar to scanf(%c%*c) like I saw someone suggest under a post with a similar problem. It did make it so the prompt to enter a character actually worked, but the loop no longer ended when Q is entered.
It looks like the issue you're facing is related to the way the newline character left in the input buffer after reading a double (with
scanf("%lf", &gradeInput)) is affecting the behaviour ofgetchar(). Thegetchar()function reads the next character from the input buffer, which includes any leftover newline characters.To fix this issue, you can clear the input buffer after reading the grade by consuming the newline character. Here's an updated version of your code:
In this code, we use a while loop to clear the input buffer by reading characters until a newline character is encountered. This ensures that any leftover characters, including the newline character, are removed from the input buffer before attempting to read the exit character. This should fix the issue and allow your loop to end when
Qorqis entered.