Ceteris paribus(格式良好的数据,良好的缓冲实践和什么不是),是否有一个原因,为什么我喜欢循环,而scanf的返回是1,而不是!EOF?我可能已经读过这个地方,或者什么,但是我也可能错了.别人怎么想?
@H_404_3@解决方法
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; }