1
输入:
一、输入不说明有多少个Input Block,以EOF为结束标志。
The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line.
C语言中,EOF常被作为文件结束的标志。还有很多文件处理函数处错误后的返回值也是EOF,因此常被用来判断调用一个函数是否成功。(如:while (scanf("%d",&n),n!=EOF) //while(scanf("%d",&n)!=EOF)也行)
#include <stdio.h>
int main()
{
int a,b;
while(scanf("%d %d",&a, &b) != EOF) printf("%d\n",a+b);
}
//--------------------------------------------------------------------------------------------------
//1. Scanf函数返回值就是读出的变量个数,如:scanf( “%d %d”, &a, &b );
//如果只有一个整数输入,返回值是1,如果有两个整数输入,返回值是2,如果一个都没有,//则返回值是-1。
//2. EOF是一个预定义的常量,等于-1。
//--------------------------------------------------------------------------------------------------
//C语法:
// while(scanf("%d %d",&a, &b) != EOF)
// {
// ....
//}
//C++语法:
// while( cin >> a >> b )
//{
// ....
//}
二、输入一开始就会说有N个Input Block,下面接着是N个Input Block。
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.
#include <stdio.h>
int main()
{
int n,i,a,b;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d %d",&a, &b);
printf("%d\n",a+b);
}
}
scanf("%d",&n) ;
for( i=0 ; i<n ; i++ )
{
....
}
cin >> n;
for( i=0 ; i<n ; i++ )
{
....
}
三、输入不说明有多少个Input Block,但以某个特殊输入为结束标志。
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.
C语法:
while(scanf("%d",&n) && n!=0 )
{ .... }
C++语法:
while( cin >> n && n != 0 ) { .... }
四、输入是一整行的字符串的
C语法: char buf[20]; gets(buf); C++语法: 如果用string buf;来保存: getline( cin , buf ); 如果用char buf[ 255 ]; 来保存: cin.getline( buf, 255 );
而getchar函数每次只接受一个字符,经常c=getchar()这样来使用。

浙公网安备 33010602011771号