stringstream
似乎總是當我打電話stringstream::ignore()
失敗,即使這調用stringstream::clear()
後進行:字符串流::忽略(INT_MAX,「 n」)導致流失敗
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cassert>
using namespace std;
int main() {
int a, b;
stringstream ss;
string str;
ifstream inFile("file.txt");
if(!inFile) {
cerr << "Fatal: Cannot open input file." << endl;
exit(1);
}
while(getline(inFile, str)) {
ss << str; // read string into ss
ss >> a >> b; // stream fails trying to store string into int
ss.clear(); // reset stream state
assert(ss.good()); // assertion succeeds
ss.ignore(INT_MAX, '\n'); // ignore content to next newline
assert(ss.good()); // assertion fails, why?
}
return 0;
}
file.txt
包含以下文本:
123 abc
456 def
爲什麼ss.ignore()
後ss.good()
假的?
最後一句:'std :: ends'不會將'\ n'放入'\ 0' – PiotrNycz
空字符可能會導致意外的行爲。 – bwDraco
@PiotrNycz:謝謝,糾正。 –