而 scanf!=EOF 还是 scanf==1? [英] While scanf!=EOF or scanf==1?

查看:80
本文介绍了而 scanf!=EOF 还是 scanf==1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ceteris paribus(格式良好的数据,良好的缓冲实践等等),有没有理由我更喜欢在 scanf 的返回值为 1 时循环,而不是比 !EOF?我可能在某处或其他地方读过这篇文章,但我也可能读错了.其他人怎么看?

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? I may have read this somewhere, or whatever, but I may have it wrong as well. What do other people think?

推荐答案

scanf 返回成功转换的项目数...或出错时的 EOF.因此,请按照有意义的方式对条件进行编码.

scanf returns the number of items succesfully converted ... or EOF on error. 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 */

人为的例子

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

这篇关于而 scanf!=EOF 还是 scanf==1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆