10
#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?

user1069968
  • 267
  • 3
  • 5
  • 14
  • Check out this article: http://www.gidnetwork.com/b-60.html – Fred Larson Nov 28 '11 at 19:18
  • 2
    possible duplicate of [Second scanf is not working](http://stackoverflow.com/questions/4023643/second-scanf-is-not-working) – AShelly Nov 28 '11 at 19:20
  • 2
    possible duplicate of [Scanf skips every other while loop in C](http://stackoverflow.com/questions/1669821/scanf-skips-every-other-while-loop-in-c) – Fred Larson Nov 28 '11 at 19:24

3 Answers3

19

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

scanf(" %c", &loop);
       ^
cnicutar
  • 178,505
  • 25
  • 365
  • 392
11

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"
sidyll
  • 57,726
  • 14
  • 108
  • 151
-2

One solution can be the use fflush(stdin) after the scanf() statement to clear the input buffer.

  • 1
    `fflush(stdin)` has undefined behavior in C programming. It might work as intended on some systems, but it is not good practice in general. – Nisse Engström Aug 07 '17 at 19:45
  • @NisseEngström Thanks Nisse, I agree with with your point. It's not a good practice as we can see here https://stackoverflow.com/questions/9122550/fflushstdin-function-does-not-work – dark_cypher Aug 14 '17 at 12:13
  • fflush stdin also work on linux but avoid use it its UB, by using it you lost portability. – EsmaeelE Nov 28 '17 at 10:07