I\'m trying to develop a simple text-based hangman game, and the main game loop starts with a prompt to enter a guess at each letter, then goes on to check if the letter is
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.
Just a guess, but you are inputting a single character with scanf, but the user must type the guess plus a newline, which is being consumed as a separate guess character.
I see a couple of things in your code:
When you enter the character, you have to enter a whitespace character to move on. This whitespace character is present in the input buffer, stdin
file, and is read by the scanf()
function.
This problem can be solved by consuming this extra character. This can be done by usnig a getchar()
function.
scanf("%c",¤tGuess);
getchar(); // To consume the whitespace character.
I would rather suggest you to avoid using scanf()
and instead use getchar()
. The scanf()
requires a lot of memory space. getchar()
is a light function. So you can also use-
char currentGuess;
currentGuess=getchar();
getchar(); // To consume the whitespace character.