I was extracting values from a stringstream in a loop, resetting the stringstream at the top of the loop every time the loop executed. However, the stringstream's >>
operator fails at the second iteration every time. This distilled version of the code reproduces the problem I'm having:
istringstream word;
string in;
int number;
while(cin >> in) {
word.str(in);
//Uncommenting either one of the following lines seems to solve the issue:
//word.clear();
//word.seekg(0);
word >> number;
if(word.fail()) {
cerr << "Failed to read int" << endl;
return 1;
}
cout << in << ' ' << number << endl;
}
As it stands, it always fails on second loop iteration. However, uncommenting any one of the two commented lines of code solves the issue. What I don't get is, since I've reset the stringstream with word.str(in)
, why does it still fail? And why does resetting the get position solve the problem?
Am I missing something about the workings of a stringstream? Does it set the eofbit
flag on the last valid read rather than on the read that fails due to EOF? And if so, why does seekg(0)
seem to clear that flag, while resetting the stringstream doesn't?