3

I just read about stringstream in C++ and implemented a simple program.

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    int num;
    stringstream sso;
    string str;

    //integer to string
    cin >> num;
    sso << num;
    sso >> str;
    cout << "String form of number : " << str << endl;

    //string to integer
    cin >> str;
    sso << str;
    sso >> num; //num still has value from previous integer to string????
    cout << "Integer form of string (+2) :" << (num + 2) << endl;
    return 0;
}

Here's the output :

12
String form of number : 12
44
Integer form of string (+2) :14

I am getting incorrect output as num is not getting updated and still holding the old value from previous calculation. What's the silly mistake am I doing?

2 Answers 2

4

After the first input operation, the stringstream gets its EOF-bit set. This bit is sticky, i.e. it doesn't get erased by adding more input to parse. As a general rule, when you read data, you should also verify that reading was successful. For streams, you can check the stream state using this:

if(!(istream >> value)) throw runtime_error("reading failed");

I'm pretty sure your second input operation simply fails, at which point the value retains its former value.

Sign up to request clarification or add additional context in comments.

Comments

3

You should clear the stringstream between use because the eofbit has been set during the first use:

sso.clear();
sso.str("");

3 Comments

Thanks. It worked. But when I did sso << str; second time in string to integer, do sso hold both the values : current as well as previous streams?
@InsaneCoder think it should fail and just retain the previous value (12)
Yes, it is failing. I put a check as per answer by @Ulrich and confirmed it. Thanks Jerome and Ulrich

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.