第一节 常用输入输出格式

  写程序,大家都会写。但是在比赛里面怎样写程序,应该按照怎样的格式去写程序,都是有严格的要求的。下面简单介绍一下各种比赛中,常见的输入输出格式。

OI

  OI比赛中,输入输出均需要使用文件操作。常见的格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
#include<stdio.h>             
int main()
{
FILE *fin,*fout;
fin=fopen("fin.txt","r");
fout=fopen("fout.txt","w");
int a,b,sum;
fscanf(fin,"%d %d",&a,&b);
sum=a+b;
fprintf(fout,"%d\n",sum);
return 0;
}

蓝桥杯

  蓝桥杯比赛对格式的要求不是很高,养成良好的代码书写习惯即可。

1
2
3
4
5
6
#include<stdio.h>             
int main()
{
printf("Hello world\n");
return 0;
}

ACM

  ACM比赛中,对输入输出的要求多种多样。因为题目都是英语,所以大家应当仔细审题,控制好输入和输出。其中,一下几种情况会经常出现。

  第一种,输入一个或一组数据。方法同蓝桥杯比赛。

1
2
3
4
5
6
#include<stdio.h>             
int main()
{
printf("Hello world\n");
return 0;
}

  第二种,输入多组数据。题目中,常见的描述方式为:The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line.

1
2
3
4
5
6
7
8
9
10
11
#include<stdio.h>                       
#include<iostream>
using namespace std;
int main()
{
int i,j;
while(scanf("%d%d",&i,&j)!=EOF) {
printf("%d\n",i+j);
}
return 0;
}

  这里我们的输入语句是写在while循环语句里面的,后面有一个!=EOF。EOF是文件结尾的标志,也就是说循环在输入结束时停止。这种输入方法在ACM中最为常见,大家应当熟练掌握。

  第三种,输入多组数据,直到遇到0,0这组数据时,停止输入。常见描述方式为:Input contains multiple test cases. Each test case contains a pair of integers a and b, one pair of integers per line. A test case containing 0 0 terminates the input and this test case is not to be processed.

1
2
3
4
5
6
7
8
9
10
11
#include<stdio.h>                     
#include<iostream>
using namespace std;
int main()
{
int i,j;
while(scanf("%d%d",&i,&j)&&(i||j)) {
printf("%d\n",i+j);
}
return 0;
}

  第四种,输入一个数字n,接下来输入n组测试数据。常见的描述方式为:Input contains an integer N in the first line, and then N lines follow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<stdio.h>               
#include<iostream>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
while(n--) {
int i,j;
scanf("%d%d",&i,&j);
printf("%d\n",i+j);
}
return 0;
}

  另外,在输入字符串时,我们可以使用gets()函数

1
2
char buf [ 20 ] ; 
gets ( buf ) ;

练习题目:hdu1089~hdu1096题