C - read scanf until feof(stdin), don't output

2019-05-31 07:20发布

I am using the scanf() function in my program to scan an integer. The way I am doing it is:

while (!feof (stdin))
if (scanf("%d", &height) != 1) { puts("Wrong input!"); return 1; }

The problem is, that after actually doing EOF, I get the wrong input and return 1, due to the scanf not returning 1. How should I solve this issue?

标签: c return scanf eof
2条回答
孤傲高冷的网名
2楼-- · 2019-05-31 08:21

As the documentation for scanf states, it will return the number of items successfully matched and assigned. This can be the number of items you gave if completely successful or any number less than that, down to zero, if it failed to match input. In the event of EOF, it will return EOF. So, check for it!

int result = scanf("%d", &height);
if (result != EOF && result != 1) {
    // We've failed!
}
查看更多
Emotional °昔
3楼-- · 2019-05-31 08:21

There are many problems with this approach. (EOF not active until after trying to read, text input like 'A' creates infinite loop, etc.) Instead :

char buf[100];
while (fgets(buf, sizeof buf, stdin) != NULL) {
  if (sscanf(buf, "%d", &height) != 1) {
    puts("Wrong input!");
    return 1;
    }
  do_something(height);
}
return 0;
查看更多
登录 后发表回答