Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read char from console

Tags:

c

scanf

getchar

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?

like image 404
Yakov Avatar asked Jan 13 '12 15:01

Yakov


2 Answers

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

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

instead of

c = getchar();
like image 77
Fred Foo Avatar answered Sep 19 '22 23:09

Fred Foo


Call fflush(stdin); after scanf to discard any unnecessary chars (like \r \n) from input buffer that were left by scanf.

Edit: As guys in comments mentioned fflush solution could have portability issue, so here is my second proposal. Do not use scanf at all and do this work using combination of fgets and sscanf. This is much safer and simpler approach, because allow handling wrong input situations.

int x,y;
char c;
char buffer[80];

printf("x:\n");
if (NULL == fgets(buffer, 80, stdin) || 1 != sscanf(buffer, "%d", &x))
{
    printf("wrong input");
}
printf("y:\n");
if (NULL == fgets(buffer, 80, stdin) || 1 != sscanf(buffer, "%d", &y))
{
    printf("wrong input");
}
c = getchar();
like image 23
Zuljin Avatar answered Sep 17 '22 23:09

Zuljin