简体   繁体   English

虽然scanf!= EOF或scanf == 1?

[英]While scanf!=EOF or scanf==1?

Ceteris paribus (well formed data, good buffering practices and what not), is there a reason why I prefer to loop while the return of scanf is 1, rather than !EOF ? Ceteris paribus (格式良好的数据,良好的缓冲实践以及其他什么),有什么理由我喜欢循环而scanf的返回值是1,而不是!EOF I may have read this somewhere, or whatever, but I may have it wrong as well. 我可能已经在某个地方读过这个,或者其他什么,但我也可能错了。 What do other people think? 其他人怎么想?

scanf returns the number of items succesfully converted ... or EOF on error. scanf返回成功转换的项目数...或出错时的EOF。 So code the condition the way it makes sense. 因此,以有意义的方式对条件进行编码。

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

Depends what you want to do with malformed input - if your scan pattern isn't matched, you can get 0 returned. 取决于您想要对格式错误的输入做什么 - 如果您的扫描模式不匹配,您可以返回0 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). 因此,如果您在循环外处理该情况(例如,如果您将其视为与输入错误相同),则与1进行比较(或者您的scanf调用中有多少项)。

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. 确保您读取预期项目数量的唯一方法是将返回值与该数字进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM