C语言中 scanf()的返回值是成功读入参数的个数

2008年11月08日 23:01 . 分类 编程相关 . 被踩 511 次 .

文章作者:Slyar 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。

忘了是谁前天问的了,本来是打算昨天写的,不过昨天有讲座写,于是乎就改今天写了。

他问我为什么 while(scanf("%d",&a)!=0) 这样的语句不能中断程序。OK,我们知道while()的参数是一个值,而这个值是scanf()函数返回的,所以我们到MSDN里面看一下相关的说明:

Both scanf and wscanf return the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end-of-file character or the end-of-string character is encountered in the first attempt to read a character.

通过这段话,我们可以知道scanf()的返回值并不是参数的值,而是成功读入参数的个数,举例说明:

scanf("%d%d",&a, &b);

如果a和b都被成功读入,scanf()的返回值是2

如果只有a被成功读入或者只有b被成功读入,scanf()的返回值为1

如果a和b都未被成功读入,scanf()的返回值为0

如果遇到错误或遇到End Of File,scanf()的返回值为EOF。

所以呢,文章开头提到的那句代码是不能正常中断程序的。

您可能还对以下内容感兴趣

收藏、分享这篇文章! 用 RSS feed 订阅本博客 什么是订阅? Trackback

评论

2 条评论 关于 “C语言中 scanf()的返回值是成功读入参数的个数”

  1. 自然堂 发表于 2008年11月09日 14:22

    很好,很有知识性喜欢

  2. felix021 发表于 2008年11月11日 21:44

    #define EOF (-1)

发表您的评论[审核后显示]




关闭
E-mail It