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
",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
",a+b);
 }
 } 
C语法:

  scanf("%d",&n) ;

  for( i=0 ; i<n ; i++ ) 

    .... 
}

C++语法:

  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 );
scanf(“ %s%s”,str1,str2),在多个字符串之间用一个或多个空格分隔;
若使用gets函数,应为gets(str1); gets(str2); 字符串之间用回车符作分隔。
通常情况下,接受短字符用scanf函数,接受长字符用gets函数。

而getchar函数每次只接受一个字符,经常c=getchar()这样来使用。 

结合后两个参数,getline可以方便地实现: 用户最多输入指定个数的字符,如果超过,则仅指定个数的前面字符有效,如果没有超过,则用户可以通过回车来结束输入。
char name[4];
cin.getline(name,4,' ');
由于 endchar 默认已经是 ' ',所以后面那行也可以写成:
cin.getline(name,4);

  

 
原文地址:https://www.cnblogs.com/songyy/p/3485422.html