Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C – While loop runs twice when it shouldn't

Hi I’m making a simple Hangman game in C

I have a while Loop that is suppose to wait for the user to input a character. However, it skips pass that on the 2nd iteration.

void startGuessing(char *word){
    char dummyWord[13];
    strcpy(dummyWord, word);

    int dummyWordLength = strlen(dummyWord);
    for (size_t i = 0; i < dummyWordLength; i++)
    {
        dummyWord[i] = '_';
    }


    int remaindingChances = 7;
    while(remaindingChances > 0){
        printf("Player 2 has so far guessed: %s\n", dummyWord);
        printf("Player 2, you have %d guesses remaining. Enter your next guess:\n", remaindingChances);

        char guess;
        guess = getchar();

        int wordLength = strlen(word);
        for (size_t i = 0; i < wordLength; i++)
        {
            if(guess == word[i]){
                dummyWord[i] = word[i];
            }
        }

        remaindingChances--;
    }
}

The following is the output I’m seeing:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Player 2 has so far guessed: ___
Player 2, you have 7 guesses remaining. Enter your next guess:
c
Player 2 has so far guessed: c__
Player 2, you have 6 guesses remaining. Enter your next guess:
Player 2 has so far guessed: c__
Player 2, you have 5 guesses remaining. Enter your next guess:

Am i doing something wrong? O.o I can’t seem to figure out this issue.

>Solution :

The simplest fix is probably to consume whitespace by replacing the guess = getchar() with something like:

int guess;
while( isspace(guess = getchar()) ) { ; }

(Note that getchar returns an int, and you should get in the habit of declaring the variable as an int.)

If you want to allow words that contain whitespace, you could use while( (guess = getchar()) != '\n' ) or similar. Whatever logic you want to use, you need to handle all the data, including the newlines. (and be aware of the possibility of \r\n on the input)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading