Ceteris (格式良好的数据、良好的缓冲实践等等),为什么我喜欢在返回scanf时循环,而不是!EOF呢?我可能在某个地方读过这篇文章,或者别的什么,但我也可能看错了。其他人怎么想?
发布于 2010-11-11 22:42:26
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 */人为实例
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 */;编辑:添加了另一个人为的示例
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;
}发布于 2010-11-11 22:43:45
取决于您想要对格式错误的输入做什么-如果您的扫描模式不匹配,您可以得到0返回。因此,如果您在循环之外处理这种情况(例如,如果您将其视为输入错误),则与1进行比较(或者您的scanf调用中有多少项)。
发布于 2010-11-11 22:46:42
来自http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
在成功的情况下,该函数将返回已连续读取的项目数。如果出现匹配失败,此计数可以匹配预期的读数数,甚至更少,甚至为零。如果在成功读取任何数据之前输入失败,则返回EOF。
确保读取预期项数的唯一方法是将返回值与该数字进行比较。
https://stackoverflow.com/questions/4159985
复制相似问题