我有這樣的代碼,關於stringstream。我發現了一個奇怪的現象:爲什麼stringstream有這種行爲?
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
int p, q;
fstream file;
string str;
stringstream sstr;
file.open("file.txt", ios::in);
if(file.is_open()) {
while(getline(file, str)) {
sstr << str;
sstr >> p >> q;
cout << p << ' ' << q << endl;
sstr.str("");
}
}
file.close();
return 0;
}
假設我有FILE.TXT作爲
4 5
0 2
在第一行第二行5
後回報和2。該計劃給了我:
4 5
4 5
這意味着p
和q
分配不正確。但我檢查了每次sstr.str()
與獲得正確的線的字符串。
爲什麼stringstream有這樣的行爲?
什麼是預期的輸出呢? – Shoe
[如何清除stringstream?](http://stackoverflow.com/questions/2848087/how-to-clear-stringstream)解決你的問題? – Lithis