C语言 而 scanf!=EOF 还是 scanf==1?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4159985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
While scanf!=EOF or scanf==1?
提问by Dervin Thunk
Ceteris paribus(well formed data, good buffering practices and what not), is there a reason why I prefer to loop while the return of scanfis 1, rather than !EOF? I may have read this somewhere, or whatever, but I may have it wrong as well. What do other people think?
其他条件相同(格式良好的数据,良好的缓冲实践等等),有没有理由我更喜欢在返回scanf为 1 而不是 1 时循环!EOF?我可能在某处或其他地方读过这篇文章,但我也可能读错了。其他人怎么看?
回答by pmg
scanfreturns the number of items succesfully converted ... or EOF on error. So code the condition the way it makes sense.
scanf返回成功转换的项目数...或出错时的 EOF。因此,以有意义的方式对条件进行编码。
scanfresult = scanf(...);
while (scanfresult != EOF) /* while scanf didn't error */
while (scanfresult == 1) /* while scanf performed 1 assignment */
while (scanfresult > 2) /* while scanf performed 3 or more assignments */
Contrived example
人为的例子
scanfresult = scanf("%d", &a);
/* type "forty two" */
if (scanfresult != EOF) /* not scanf error; runs, but `a` hasn't been assigned */;
if (scanfresult != 1) /* `a` hasn't been assigned */;
Edit: added another more contrived example
编辑:添加了另一个更人为的例子
int a[5], b[5];
printf("Enter up to 5 pairs of numbers\n");
scanfresult = scanf("%d%d%d%d%d%d%d%d%d%d", a+0,b+0,a+1,b+1,a+2,b+2,a+3,b+3,a+4,b+4);
switch (scanfresult) {
case EOF: assert(0 && "this didn't happen"); break;
case 1: case 3: case 5: case 7: case 9:
printf("I said **pairs of numbers**\n");
break;
case 0:
printf("What am I supposed to do with no numbers?\n");
break;
default:
pairs = scanfresult / 2;
dealwithpairs(a, b, pairs);
break;
}
回答by Steve Jessop
Depends what you want to do with malformed input - if your scan pattern isn't matched, you can get 0returned. So if you handle that case outside the loop (for example if you treat it the same as an input error), then compare with 1(or however many items there are in your scanf call).
取决于您想对格式错误的输入做什么 - 如果您的扫描模式不匹配,您可能会被0退回。因此,如果您在循环外处理这种情况(例如,如果您将其视为输入错误),则与1(或您的 scanf 调用中有多少项进行比较)。
回答by Mark Ransom
From http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
来自http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
On success, the function returns the number of items succesfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.
成功时,该函数返回成功读取的项目数。如果发生匹配失败,此计数可以匹配预期的读数数量或更少,甚至为零。如果在成功读取任何数据之前输入失败,则返回 EOF。
The only way to be sure that you read the number of items intended is to compare the return value to that number.
确保您读取预期项目数的唯一方法是将返回值与该数字进行比较。

