官方說明: (1) istream&getline(istream&is,string&str,char delim); istream&getline(istream && is,string&str,char delim); (2) istream&getline(istream&is,string&str); istream&getline(istream && is,string&str); 從流中獲取行字符串 從is中提取字符並將它們存儲到str中,直到找到分隔字符delim(或換行符,(2)中默認為'\ n')。
is:
istream object from which characters are extracted.
str:
string object where the extracted line is stored.
The contents in the string before the call (if any) are discarded and replaced by the extracted line.
例如:
第一行輸入一個n,代表接下來輸入n行字符串(每行字符串可以包含空格)
3 aa aa bbb ccc
#include <iostream> #include <vector> using namespace std; int main() { vector<string> vec; int n; cin >> n; cin.get();//由於輸入n之后回車,使用這句回車符號吃掉,否則下面的getline()獲取的第一個字符串為'\n' while(n--) { string s; getline(cin, s); //默認為回車符,若以其他符號為分隔符,改為getline(cin, s, ','),例如逗號 vec.push_back(s); } cout<< "result: " <<endl; for(int i=0; i<vec.size(); ++i) { cout << vec.at(i) << endl; } system("pause"); return 0; }
若沒有cin.getr()將 '\n' 吃掉,則會出現以下情況:
輸入兩次便不可在輸入,輸出結果中第一行為空(只有一個回車符號,所以顯示為空)
