Home > front end >  C - While loop runs twice when it shouldn't
C - While loop runs twice when it shouldn't

Time:11-01

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:

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.

CodePudding user response:

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)

CodePudding user response:

Consider using

scanf(" %c", &guess);

for your input. You can implement further logic to to make sure the input is a letter, but this should fix your current problem

  •  Tags:  
  • c
  • Related