Printf being executed twice during a loop

2

I am creating a prototype of the gallows game. I do not understand much of programming and I have a problem with what is returned. The part of the code that is giving problem and that is below returns me twice the "Type a letter:". Can anyone 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] != '
  for(chance = 1; chance <= 10; chance++)
       {
        printf("\n");
        printf("Digite uma letra: ");
        scanf("%c", &letra);
        printf("\n");
        for(i = 0;word[i] != '%pre%';i++)
        {
            if(letra == word[i])
            {
                var[i*2] = letra;
            }
        }
        printf("%s\n", var);
';i++) { if(letra == word[i]) { var[i*2] = letra; } } printf("%s\n", var);

    
asked by anonymous 22.11.2016 / 00:57

1 answer

0

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

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

    
22.11.2016 / 01:17