+ 2
Problem with printf in loop
Just a begginer in C. I'm trying to make a program that continually asks to play again in a loop, waits for input, and depending on that input, either loops again or stops. EXAMPLE (Of what I'm going for): Play game? [y/n] > y //enter y or n after prompt Play again? [y/n] > y //enter y or n after prompt ... ... Play again? [y/n] > n //when n, the program stops Stopping! I tried the debugger and found that it skips right over the second printf statement and the ans variable in the program changes to a '\n' character after the initial assigning. I can't figure out why, can anyone shed some light? https://code.sololearn.com/cqUCiDuUEvFD/?ref=app
6 ответов
+ 4
Slick whenever you input a character using scanf() then it just reads one character but the "\n" still lives in buffer and gets read whenever you try to read another character
This leads your program to exit in first iteration as the next scanf() is reading '\n' character instead of user input.
A simple fix is to use getchar() to read and ignore that '\n' in the buffer.
Here👇
https://code.sololearn.com/cl6CrqT2iUdt/?ref=app
+ 2
Thanks Arsenic, I gotta do some more learning on getchar(). I was thinking you either use getchar() OR scanf() not both.
+ 2
Slick getchar() is used to read only one character from the input buffer.
I am using it to just read that extra charater which is left in the buffer.
+ 2
Another simpler way to deal with such anomaly (the remaining white spaces in the input buffer), which causes the next `scanf()` in the chain of prompts consumes the remnant of the previous one, is by putting a single space before each conversion specifier as
...
/* the very first scanf */
scanf(" %c", &c1);
...
/* the second one */
scanf(" %c", &c2);
...
/* the nth one */
scanf(" %c", &cn);
+ 1
People also use fflush(stdin) to flush the input buffer but I don't preffer it as it is originally designed to flush the output buffer so using it for input buffer may lead to unpredictable consequences.
+ 1
Arsenic I was seeing that as well on some search results. A big thing I figured out is that I don't know enough about this input buffer. So thanks for that I'll check that out too.