Scanf skips every other while loop in C

前端 未结 10 1833
清歌不尽
清歌不尽 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: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",¤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.
    

提交回复
热议问题