read char from console

Yakov picture Yakov · Jan 13, 2012 · Viewed 52k times · Source

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?

Answer

Fred Foo picture Fred Foo · Jan 13, 2012

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

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

instead of

c = getchar();