c++getline和get的區別

來源:互聯網
上載者:User

getline()和get()這兩個函數都讀取一行的輸入,直到達到分行符號。然而不同的是gerline()將丟棄分行符號,而get()將分行符號保留在輸入序列中。

(1)getline

#include <iostream>using namespace std;const int SIZE = 15;int main(){    char name[SIZE];    char dessert[SIZE];    cout << "Enter your name:";    cin.getline(name, SIZE);    cout << "Enter your favorite dessert:";    cin.getline(dessert, SIZE);    cout << " I have some delicious " << dessert;    cout << "for you," << name << ".\n";    return 0;}

結果:

該程式可以讀取完整的姓名以及使用者喜歡的甜點,是因為getline()函數每次讀取一行,它通過分行符號來確定行尾,但不儲存分行符號。也就是他會拋棄有Enter鍵產生的分行符號,並將分行符號替換為空白字元。

(2)get()
get()函數不再讀取並丟棄分行符號,二是將分行符號儲存到隊列中,假設我們連續兩次調用get()
cin.get(name,ArSize);
cin.get(dessert,ArSize);
由於第一次調用後,分行符號將留在輸入隊列中,因此第二次調用時看到的第一個字元便是分行符號,get()會認為已經到達行位,沒有發現可讀取的內容,如果沒有其他協助,將不能跨過該分行符號。

#include <iostream>using namespace std;const int SIZE = 20;int main(){    char name[SIZE];    char dessert[SIZE];    cout << "Enter your name:";    cin.get(name, SIZE);    cout << "Enter your favorite dessert: ";    cin.get(dessert, SIZE);    cout << "I have some delicious " << dessert;    cout << " for you," << name << ".\n";    return 0;}

運行結果,第二個get()看到的第一個字元是第一個get()儲存下來的分行符號,所以第二個沒有輸入就直接進入下一行了。

解決這個問題的方法就是使用一個不帶任何參數的cin.get()調用可讀取下一個字元,因此通常用這種方法來處理分行符號。
cin.get(name,ArSize);
cin.get();
cin.get(dessert,ArSize);
我們將上述程式改為

    cout << "Enter your name:";    cin.get(name, SIZE).get();    cout << "Enter your favorite dessert: ";    cin.get(dessert, SIZE);    cout << "I have some delicious " << dessert;    cout << " for you," << name << ".\n";

程式運行結果為
可見,分行符號被處理掉了。

關於更多的輸入字串和數位問題,可以參考c++primer plus 第四章P81.

聯繫我們

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