C++每次讀取一行字串輸入(學習筆記)

來源:互聯網
上載者:User

標籤:

1. 面向行的輸入:getline()
getline()函數讀取整行,它使用通過斷行符號鍵輸入的分行符號來確定輸入結尾。
cin.getline(Arr, 20) // Arr為用來輸入行的數組的名稱;
                       //20包括19個字元和1個Null 字元  

2. 面向行的輸入:get()
與getline()的工作方式類似,接受參數相同,但get()並不再讀取並丟棄分行符號,而是將其留在輸入隊列中。可如下使用:
cin.get(Arr1, ArSize); // 讀第一行
cin.get();             // 讀掉分行符號
cin.get(Arr2, ArSize2); // 讀第二行

////////////////////////////////////////或者

cin.get(Arr1, ArSize).get();
cin.get(Arr2, ArSize2);

3. 字串輸入:getline(cin, srt)
getline(cin, str); // str為string類型  getline()需要#include<string>

4. 輸入時遇錯誤類型時
int int nTemp;
cout << "Please enter handicap(int): " << endl;
    while (!(cin >> nTemp))
    {
        cin.clear();//重設輸入,如果省略這條,程式將拒絕繼續讀取輸入
        while (cin.get() != ‘\n‘)//本迴圈使用 cin.get() 來讀取尾行之前的所有輸入,從而刪除這一行
            continue;
        cout << "Please input a integer: ";
    }

 

 

C++每次讀取一行字串輸入(學習筆記) (轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.