Scanf skips every other while loop in C

前端 未结 10 1819
清歌不尽
清歌不尽 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:21

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

    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.

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

    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.

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

    I see a couple of things in your code:

    1. scanf returns the number of items it read. You will probably want to handle the cases where it returns 0 or EOF.
    2. My guess would be that the user is hitting letter + Enter and you're getting the newline as the second character. An easy way to check would be to add a debugging printf statement to show what character was entered.
    3. Your code will only match the first occurrence of a match letter, i.e. if the word was "test" and the user entered 't', your code would only match the first 't', not both. You need to adjust your first loop to handle this.
    0 讨论(0)
  • 2020-11-22 02:24

    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",&currentGuess);  
    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.
    
    0 讨论(0)
提交回复
热议问题