0

There's a small error in this C code. After the user's input causes the program to enter the while loop (error handling) - that the while loop iterates twice?!

Something to do with the scanf() or printf() ?

The output:

Would you like to interact with this program today? (y/n

Please answer the question by typing 'y' or 'n' and hitting enter
Would you like to interact with this program today? (y/n)

Please answer the question by typing 'y' or 'n' and hitting enter
Would you like to interact with this program today? (y/n)

The code:

printf("\nWould you like to interact with this program today? (y/n)\n");
char answer; // recording the user's answer in a character
scanf("%c", &answer);

while ((answer != 'y') && (answer != 'n')) { // keeps looping twice???
    printf("\nPlease answer the question by typing 'y' or 'n' and hitting enter\n");
    printf("Would you like to interact with this program today? (y/n)\n");
    scanf("%c", &answer);
}
F. Müller
  • 3,969
  • 8
  • 38
  • 49
  • 1
    When you type “f” and press Enter, there are two characters in the input stream: an f and a new-line character. The `scanf(“%c”,…)` reads both of them, one at a time. – Eric Postpischil Aug 16 '20 at 02:14
  • @CharlesSrstka Calling the `fflush` on an input stream is undefined behaviour. See [Using fflush(stdin)](https://stackoverflow.com/questions/2979209/using-fflushstdin). – M. Nejat Aydin Aug 16 '20 at 02:21

0 Answers0