码迷,mamicode.com
首页 > 其他好文 > 详细

ACM基础之四种输入类型及常见实现方法

时间:2015-09-02 23:19:25      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:

输入_第一类

  •    输入不说明有多少个Input Block,以EOF为结束标志。

     例题(HDOJ1089)

Problem 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 5
10 20
Sample Output
6
30
  本类输入解决方法
  C语法:

  while(scanf("%d %d",&a, &b) != EOF)//1.Scanf函数返回值就是读出的变量个数,如:scanf( “%d  %d”, &a, &b );
   {                                     如果只有一个整数输入,返回值是1,如果有两个整数输入,返回值是2,如果一个都没有,则返回值是-1

       ....                            2.EOF是一个预定义的常量,等于-1
  }                                 

  C++语法:

  while( cin >> a >> b )
  {
    ....
  }

  Java语法:

  Scanner scan=new Scanner(System.in);

  while(scan.hasNext()){

    a=scan.nextInt();

    b=scan.nextInt();

    ....

  }

输入_第二类
  • 输入一开始就会说有N个Input Block,下面接着是N个Input Block。

      例题(HDOJ1090)

      本类输入解决方法

  C语法:

  scanf("%d",&n) ;

  for( i=0 ; i<n ; i++ )
{
    ....
}

  C++语法:

  cin >> n;
for( i=0 ; i<n ; i++ )
{
    ....
}

 java语法:

n=scan.nextInt();

for( i=0 ; i<n ; i++ )
{
    ....
}

输入_第三类

  • 输入不说明有多少个Input Block,但以某个特殊输入为结束标志。

     例题(HDOJ1091)

     本类输入解决方法

C语法:

  while(scanf("%d",&n)  && n!=0 )

  {
    ....
}

C++语法:

  while( cin >> n && n != 0 )
{
    ....
}

Java语法:

while( n=scan.nextInt&&n!=0 )
{
    ....
}

输入_第五类

  • 输入是一整行的字符串的

    例题(HDOJ1048)

  C语法:

    char buf[20];
    gets(buf);

  C++语法:

  如果用string buf;来保存:

   getline( cin , buf );

  如果用char buf[ 255 ]; 来保存:
  cin.getline( buf, 255 );//

 getline 是一个函数,它可以接受用户的输入的字符,直到已达指定个数,或者用户输入了特定的字符。它的函数声明形式(函数原型)如下:

 istream& getline(char line[], int size, char endchar = ‘\n‘);

 不用管它的返回类型,来关心它的三个参数:
 char line[]: 就是一个字符数组,用户输入的内容将存入在该数组内。
 int size : 最多接受几个字符?用户超过size的输入都将不被接受。
 char endchar :当用户输入endchar指定的字符时,自动结束。默认是回车符。
 Java语法:
 scan.nextLine();

ACM基础之四种输入类型及常见实现方法

标签:

原文地址:http://www.cnblogs.com/djl5880/p/4779533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!