(1) istream& getline (istream& is, string& str, char delim); (2) istream& getline (istream& is, string& str);
由getline的定義可以知道, getline返回的是一個輸入流, 正常情況下輸入流都是正確的, 因而
while(getline(cin, str));
是一個死循環無法跳出;
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).
The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).
Note that any content in str before the call is replaced by the newly extracted sequence.
Each extracted character is appended to the string as if its member push_back was called.
有定義可以知道, getline把分隔符delim之前的字符全部保存在str中, 包括空格等; 此外分隔符delim也會被吸收但是不會被保存到str中
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 int main(){ 5 string str; 6 getline(cin, str, 'A'); 7 cout<<"The string we have gotten is :"<<str<<'.'<<endl; 8 getline(cin, str, 'B'); 9 cout<<"The string we have gotten is :"<<str<<'.'<<endl; 10 return 0;}
為了便於觀察, 用_代替空格; 這里我們分別以'A', 'B'作為字符串輸入的終止符;
通過上面的輸出可以發現'A', 'B'都不在輸出字符串中, 表示這兩個字符都沒有被保存在輸入字符串中;
此外, 當delim沒有顯示的給出的時候, 默認為'\n'