scanf返回值的问题

scanf返回值的问题

关于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 nocountered in the first attempt to read a character.
如:
scanf("%d%d", &a, &b);
如果a和b都被成功读入,那么scanf的返回值就是2
如果只有a被成功读入,返回值为1
如果a和b都未被成功读入,返回值为0
如果遇到错误或遇到end of file,返回值为EOF。不经意中发现scanf()的返回值问题,自己试验和了解了一下,一些所知与各位分享; 
void main() 

int a; 
int b; 
int c; 
printf("请输入三个整数:"); 
int x=scanf("%d%d%d",&a,&b,&c); 
printf("%d\n%d\n",a,x); 

1.scanf()函数有返回值且为int型。 
2.scanf()函数返回的值为:正确按指定格式输入变量的个数;也即能正确接收到值的变量个数。 
从上边的例子中可以得到验证,这里用变量x接收scanf()函数的返回值,并输出显示出来。当运行中输入三个整数:5 6 7则x的值为3;如果输入5 6 d(即给c 赋值不正确)则x的值为2;如果输入5 t d(即给b和c 赋值不正确)则x的值为1; 

其实scanf()的返回值对我们来说也很有用的,比如我们在使用这个函数进行接收值时,我们很必要知道对要给赋值的变量是否正确的赋值成功了,所以可以使用if(scanf("%d,%d",&a,&b)==2)这样语句来判断是否正确的给所有的变量赋值了,正确的话才能使用这个变量参与运算,这样才能提高我们代码的安全性,所以这个返回值也是大有用途的.(转)。
posted @ 2014-04-25 16:38  CloudPing  阅读(332)  评论(0编辑  收藏  举报