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
scanf(" %c", &fooBar);
Notice the space before the %c
. This is important, because it matches all preceding whitespace.
The first time through the loop, scanf() reads the character. Then it reads the newline. Then it reads the next character; repeat.
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)
{
...
}
Jim and Jonathan have it right.
To get your scanf line to do what you want (consume the newline character w/o putting it in the buffer) I'd change it to
scanf("%c\n", ¤tGuess);
(note the \n
)
The error handling on this is atrocious though. At the least you should check the return value from scanf against 1, and ignore the input (with a warning) if it doesn't return that.
I'll guess: your code is treating a newline as one of the guesses when you enter data. I've always avoided the *scanf() family due to uncontrollable error handling. Try using fgets() instead, then pulling out the first char/byte.
A couple points I noticed:
scanf("%c")
will read 1 character and keep the ENTER in the input buffer for next time through the loopi
even when the character read from the user doesn't match the character in secretWord
covered[j]
ever get to be '-'?Break the problem up into smaller parts:
int main(void) {
char val;
while (1) {
printf("enter val: ");
scanf("%c", &val);
printf("got: %d\n", val);
}
}
The output here is:
enter val: g
got: 103
enter val: got: 10
Why would scanf
give you another '10' in there?
Since we printed the ASCII number for our value, '10' in ASCII is "enter" so scanf
must also grab the "enter" key as a character.
Sure enough, looking at your scanf
string, you are asking for a single character each time through your loop. Control characters are also considered characters, and will be picked up. For example, you can press "esc" then "enter" in the above loop and get:
enter val: ^[
got: 27
enter val: got: 10