read char from console

2019-02-16 17:18发布

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?

标签: c scanf getchar
5条回答
戒情不戒烟
2楼-- · 2019-02-16 18:02

A way to clean up anyspace before your desired char and just ignore the remaining chars is

do {
    c = getchar();
} while (isspace(opcao));
while (getchar() != '\n');
查看更多
爷的心禁止访问
3楼-- · 2019-02-16 18:04

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();
查看更多
做自己的国王
4楼-- · 2019-02-16 18:07

You can use the fflush function to clear anything left in buffer as a consquence of previous comand line inputs:

fflush(stdin);
查看更多
走好不送
5楼-- · 2019-02-16 18:07

For a start the scanf should read scanf("%d\n", &x); or y. That should do the trick.

man scanf

查看更多
霸刀☆藐视天下
6楼-- · 2019-02-16 18:11

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

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

instead of

c = getchar();
查看更多
登录 后发表回答