stringstream always seems to fail when I call stringstream::ignore(), even if this is done after calling stringstream::clear():
#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 contains the following text:
123 abc
456 def
Why is ss.good() false after ss.ignore()?
std::endloutputs\nand flushes the stream. However,stringstream::flush()is meaningless and does nothing.flushonly has meaning when the underlying buffer is tied to an output device like the terminal, however, astringstreamhas nowhere to flush the contents to. If you want to clear the contents of a stringstream doss.str("");instead. However, I would probably change the code to the following:Also, if you want to insert a newline into the stringstream, just do
ss << '\n';and do not callstd::endl.