文章作者:姜南(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。
所以呢,文章开头提到的那句代码是不能正常中断程序的。
转载请注明:Slyar Home » C语言中 scanf()的返回值是成功读入参数的个数