首页 » 网站推广 » phpscanf函数技巧_C措辞关于scanf函数的返回值

phpscanf函数技巧_C措辞关于scanf函数的返回值

访客 2024-12-07 0

扫一扫用手机浏览

文章目录 [+]

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

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

phpscanf函数技巧_C措辞关于scanf函数的返回值

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

phpscanf函数技巧_C措辞关于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=%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 510 20

【Sample Output】

630

其源代码为:

#include <stdio.h>

int main()

{

int a,b;

while(scanf(\"大众%d %d\公众,&a, &b) != EOF)

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

return 0;

}

标签:

相关文章