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

爱⌒轻易说出口 提交于 2019-12-08 06:11:47

问题


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?


回答1:


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!
}



回答2:


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;


来源:https://stackoverflow.com/questions/20034876/c-read-scanf-until-feofstdin-dont-output-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!