Scanf skips every other while loop in C

前端 未结 10 1834
清歌不尽
清歌不尽 2020-11-22 01:55

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

相关标签:
10条回答
  • 2020-11-22 02:05
    scanf(" %c", &fooBar);
    

    Notice the space before the %c. This is important, because it matches all preceding whitespace.

    0 讨论(0)
  • 2020-11-22 02:07

    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)
    {
        ...
    }
    
    0 讨论(0)
  • 2020-11-22 02:08

    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", &currentGuess);
    

    (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.

    0 讨论(0)
  • 2020-11-22 02:11

    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.

    0 讨论(0)
  • 2020-11-22 02:14

    A couple points I noticed:

    • scanf("%c") will read 1 character and keep the ENTER in the input buffer for next time through the loop
    • you're incrementing i even when the character read from the user doesn't match the character in secretWord
    • when does covered[j] ever get to be '-'?
    0 讨论(0)
  • 2020-11-22 02:20

    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
    
    0 讨论(0)
提交回复
热议问题