关于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;
int x;
printf("请输入三个整数:/n");
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;如果输入
d 5 2 则输出-858993460和0,也就是说第一个字符d输入错误,整个scanf没有收到输入值。


其实scanf()的返回值对我们来说也很有用的,比如我们在使用这个函数进行接收值时,我们很必要知道对要给赋值的变量是否正确的赋值成功了,所以可以使用if(scanf("%d,%d",&a,&b)==2)这样语句来判断是否正确的给所有的变量赋值了,正确的话才能使用这个变量参与运算,这样才能提高我们代码的安全性,所以这个返回值也是大有用途的。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值