David
David

Reputation: 165

C++ correct use of stringstream::str()?

Consider the following C++ program:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main (void)
{
    string l1, l2;
    int n1, n2;
    stringstream ss;
    getline(cin, l1);
    getline(cin, l2);
    cerr << l1 << " " << l2 << endl;
    ss.str(l1);
    ss >> n1;
    ss.str(l2);
    ss >> n2;
    cerr << n1 << " " << n2 << endl;

    return 0;
}

Sample input:

2
3

Corresponding output:

2 3
2 0

But I was expecting:

2 3
2 3

If I insert a call ss.clear() before the second call to ss.str(), the output is what I expected. Is this really necessary? And why?

Upvotes: 3

Views: 1228

Answers (1)

Dave S
Dave S

Reputation: 21113

It is necessary, because the first input from the stringstring hits end of file. Calling str() does not clear any error flags that are already set on the stringstream.

 ss.str(l1);
 ss >> n1; // Reads the entire buffer, hits the end of buffer and sets eof flag
 ss.str(l2); // Sets the string, but does not clear error flags
 ss >> n2; // Fails, due to at EOF

You can use clear before the second str() or after, just as long as it's before you attempt to read more data.

Upvotes: 3

Related Questions