Printf running twice during a loop

Asked

Viewed 540 times

3

I’m creating a prototype hangman game. I don’t know much about programming and I have a problem with what is returned. The part of the code that is giving problem and below returns me twice the "Type a letter: ". Someone knows tell me the reason?

  for(chance = 1; chance <= 10; chance++)
       {
        printf("\n");
        printf("Digite uma letra: ");
        scanf("%c", &letra);
        printf("\n");
        for(i = 0;word[i] != '\0';i++)
        {
            if(letra == word[i])
            {
                var[i*2] = letra;
            }
        }
        printf("%s\n", var);

Retorno

1 answer

1

If you put a printf("%d",chance); in your loop, you will see that it runs twice to each character you place, ie the scanf is running twice with a character. This is because when you type, for example, the letter 'a', then he has to press enter, so he actually reads two characters, a 'a' and a '\n'. As his scanf only reads one character, the '\n' which comes later is saved in the buffer to be read later, that is, in the next loop iteration. When comes the next scanf, he reads the \n. That’s why he runs twice.

To solve this problem, put a space before the %c of your scanf, exactly this way: scanf(" %c", &letra);. So your '\n' is "read" by the empty character. My tests ran correctly here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.