scanf 返回值_关于scanf()函数的返回值

在学习C语言时,通常使用scanf()函数获得从键盘输入的数据。

那么scanf()函数有返回值吗?回答是肯定的。

1.scanf()函数有返回值且为int型。

2.scanf()函数返回的值为:正确按指定格式输入变量的个数,也即能正确接收到值的变量个数。

例如:

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

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

如果只有a被成功读入,返回值为1;

如果a和b都未被成功读入,返回值为0;

如果遇到错误或遇到end of file,返回值为EOF。EOF是一个预定义的常量,等于-1。#define EOF -1

我们可以通过下面的代码得到验证。

#include

int main(void)

{

int a;

int b;

int c;

int x;

printf("请输入三个整数:\n");

x=scanf("%d%d%d",&a,&b,&c);

printf("x=%d\n", x);

}

这里用变量x接收scanf()函数的返回值,并输出显示出来。

上述代码要求运行中输入三个整数:

如果输入5 6 7,则x的值为3;

如果输入5 6 d(即给c 赋值不正确),则x的值为2;

如果输入5 t d(即给b和c 赋值不正确),则x的值为1;

如果输入d 5 2 则输出x=0,也就是说第一个字符d输入错误,整个scanf()没有收到输入值。

其实scanf()的返回值是很有用的,比如在使用这个函数进行接收值时,我们有必要知道对要给赋值的变量是否正确的赋值成功了,所以可以使用if(scanf("%d,%d",&a,&b)==2)这样语句来判断是否正确地给所有的变量赋值,正确的话才能使用这个变量参与运算,这样才能提高代码的安全性。

例如,下面的问题就需要借助于scanf()返回值作为循环的条件。

输入不说明有多少个Input Block,以EOF为结束标志。

参见:HDOJ_1089(http://acm.hdu.edu.cn/showproblem.php?pid=1089)

A+B for Input-Output Practice (I)

【Problem Description】

Your task is to Calculate a + b.
Too easy?! Of course! I specially designed the problem for acm beginners. You must have found that some problems have the same titles with this one, yes, all these problems were designed for the same aim.

【Input】

The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line.

【Output】

For each pair of input integers a and b you should output the sum of a and b in one line, and with one line of output for each line in input.

【Sample Input】

1 5
10 20

【Sample Output】

6
30

其源代码为:

#include

int main(void)

 {

int a,b;

while(scanf("%d %d",&a, &b) != EOF) 

printf("%d\n",a+b);

return 0;

}

065f047ff0b7a7ab730d24ac3ce96b9e.png

9b5050e7e468eacf30dee0b574c96bf2.png

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值