我一直在試圖將輸入字符串拆分成由空格描述的更小的字符串。我發現這個代碼here:C++ Stringstream:接受一個字符串,但不接受變量中存儲的字符串。爲什麼?
stringstream ss ("bla bla");
string s;
while (getline(ss, s, ' ')) {
cout << s << endl;
}
它工作得很好。但是,如果用包含字符串的變量替換「bla bla」:
string userInput;
cin >> userInput;
stringstream ss (userInput);
string s;
while (getline(ss, s, ' ')) {
cout << s << endl;
}
只打印出第一個字/字符/字符串。這是爲什麼?有沒有辦法解決它?我瀏覽過一些stringstream問題,但問題是我並不真正知道我在找什麼。
請出示和初始化條件是'stringstream'「含有字符串的變量」的一個例子。 – Xeo 2012-03-09 09:31:43
適合我。 – 2012-03-09 09:39:38
看起來對我有用:http://ideone.com/1AvVV。 – 2012-03-09 09:42:24