C-读取scanf直到feof(stdin),不输出错误 [英] C - read scanf until feof(stdin), don't output error
问题描述
我正在程序中使用scanf()函数来扫描整数。我这样做的方式是:
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; }
问题是,在实际执行EOF之后,我得到了错误的输入并返回1,到scanf不返回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?
推荐答案
作为 scanf的文档
状态,它将返回成功匹配和分配的项目数。如果完全成功,则可以是您给定的项目数;如果输入不匹配,则可以是小于零的任何项目数(低至零)。如果发生EOF,它将返回EOF。因此,请检查它!
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!
}
这篇关于C-读取scanf直到feof(stdin),不输出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!