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.