文档介绍:2017-5-71 ACM 程序设计输入输出格式 2017-5-72ACM 题目特点由于 ACM 竞赛题目的输入数据和输出数据一般有多组(不定),并且格式多种多样,所以,如何处理题目的输入输出是对大家的一项最基本的要求。这也是困扰初学者的一大问题。下面,分类介绍: 2017-5-73一个超级简单的题目( ex-1 ): ? Problem Description Your task is to calculate a + b. ? 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 2017-5-74初学者很常见的一种写法: ?#include< > ? void main() ?{ ? int a,b ; ? scanf( “%d % d”,&a,&b ); ? Printf( “%d ”,a+b ); ?} 2017-5-75有什么问题呢? 这就是下面需要解决的问题基本输入输出 2017-5-76输入第一类: ?输入不说明有多少个 Input Block, 以 EOF 为结束标志。参见:ex-1. 2017-5-77 ex-1 源代码: #include < > int main() { int a,b ; while(scanf("%d % d",&a , &b) != EOF) printf("%d\n",a+b ); } 2017-5-78本类输入解决方案: ?C语法: while(scanf("%d % d",&a , &b) != EOF) { .... } ? C++ 语法: while( cin >> a >> b ) { .... } 2017-5-79说明: 1. Scanf 函数返回值就是读出的变量个数,如: scanf ( “%d %d ”, &a, &b ); 如果 a和b都被成功读入整数,那么 scanf 的返回值就是 2; 如果只有 a被成功读入整数,返回值为 1; 如果 a和b都未被成功读入整数,返回值为 0; 如果遇到错误或遇到 end of file ,返回值为 EOF 2. EOF 是一个预定义的常量,等于-1。 2017-5-7 10 输入第二类: ?输入一开始就会说有 N个 Input Block, 下面接着是 N个 Input Block 。 ex-2 ? Problem Description Your task is to calculate a + b. ? Input Input contains an integer N in the first line, and then N lines follow. Each line consists of a pair 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 2 1 5 10 20 ? Sample output 6 30