Search code examples
cscanfgetchar

read char from console


I write console application which performs several scanf for int And after it ,I performs getchar :

int x,y;
char c;
printf("x:\n");
scanf("%d",&x);
printf("y:\n");
scanf("%d",&y);
c = getchar();

as a result of this I get c = '\n',despite the input is:

1
2
a

How this problem can be solved?


Solution

  • This is because scanf leaves the newline you type in the input stream. Try

    do
        c = getchar();
    while (isspace(c));
    

    instead of

    c = getchar();