Scanf skips every other while loop in C
Solution 1:
When you read keyboard input with scanf()
, the input is read after enter is pressed but the newline generated by the enter key is not consumed by the call to scanf()
. That means the next time you read from standard input there will be a newline waiting for you (which will make the next scanf()
call return instantly with no data).
To avoid this, you can modify your code to something like:
scanf("%c%*c", ¤tGuess);
The %*c
matches a single character, but the asterisk indicates that the character will not be stored anywhere. This has the effect of consuming the newline character generated by the enter key so that the next time you call scanf()
you are starting with an empty input buffer.
Caveat: If the user presses two keys and then presses enter, scanf()
will return the first keystroke, eat the second, and leave the newline for the next input call. Quirks like this are one reason why scanf()
and friends are avoided by many programmers.
Solution 2:
Newlines.
The first time through the loop, scanf() reads the character. Then it reads the newline. Then it reads the next character; repeat.
How to fix?
I seldom use scanf(), but if you use a format string "%.1s"
, it should skip white space (including newlines) and then read a non-white space character. However, it will be expecting a character array rather than a single character:
char ibuff[2];
while ((scanf("%.1s", ibuff) == 1)
{
...
}