While-loop ignores scanf the second time

#include <stdio.h>

int main ()
{
    char loop='y';
    while(loop != 'n') {
        printf("loop? ");
        scanf("%c", &loop);
        if(loop != 'y') {
            loop='n';
        }
    }
    return 0;
}

If I type in 'y' he restart the while-loop but ignores the scanf the second time and end the loop after that. Can anyone help?


Solution 1:

Make sure the scanf discards the newline. Change it to:

scanf(" %c", &loop);
       ^

Solution 2:

You probably had to enter a newline so the input goes to your program, right? The second time your loop executes it reads that newline character, which was "waiting" to be read and automatically exits the loop ('\n' != 'y'). You can make scanf ignore whitespace by using this format string instead:

" %c"