c语言中scanf的返回值(C语言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

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

int main()

{

int a;

int b;

int c;

int x;

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

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

printf("x=%dn", 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 <stdio.h>

int main()

{

int a,b;

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

printf("%dn",a+b);

return 0;

}

c语言中scanf的返回值(C语言scanf返回值)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发表评论

登录后才能评论