ACM基礎之四種輸入類型及常見實現方法

來源:互聯網
上載者:User

標籤:

輸入_第一類

  •    輸入不說明有多少個Input Block,以EOF為結束標誌。

     例題(HDOJ1089)

Problem DescriptionYour 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. InputThe input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line. OutputFor 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 Input1 510 20Sample Output630  本類輸入解決方案  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++文法:

  如果用stringbuf;來儲存:

   getline(cin , buf );

  如果用charbuf[ 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基礎之四種輸入類型及常見實現方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.