ACM简单题目中对于连续多组输入的处理方法

来源:互联网 发布:悟空理财 知乎 编辑:程序博客网 时间:2024/05/01 04:31

首先挂一道例题:

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

这道题中提到了a series of pairs of integers

意味着需要输入多组数据进行计算和输出

这里分别给出使用C和C++实现的代码样例

C语言样例:

#include<stdio.h>int main(){int a,b;while(scanf("%d%d",&a,&b)!=EOF)printf("%d\n",a+b);return 0;}

(代码已测试通过)


在C语言中输入函数scanf()具有返回值,函数返回值为int型。

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

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

如果a和b都未被成功读入,返回值为0;如果遇到错误或遇到end of file,返回值为EOF

因此可以使用

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

来实现多组输入(判断是否遇到错误或end of file)。




//C++样例

#include<iostream>using namespace std;
int main(){int a,b;while(cin>>a>>b)cout<<a+b<<endl;return 0;}

(已测试通过)

cin和scanf()函数略有区别。

首先cin是个对象,没有所谓返回值:

>>输入操作符返回流对象的引用,cin >> x 返回istream&;

cout << x返回oostream&。


但是和scanf()相似的是,可以用if直接判断,如if (cin)
或使用while间接判断,如while (cin >> x)
若流被标记错误(读取失败)就返回false;
ctrl+z,F6可跳出循环,这代表eof(文件结束符);

另外,当在缓冲区读取到的数据与>>后面的变量类型不匹配的时候也会结束。

比如说如果a,b是int的,你如果在下面的cin>>a>>b;里面输入的是非int的(比如说是‘a'或其它)也会结束。



0 0