InsaneCoder
InsaneCoder

Reputation: 8268

Stringstream string to integer conversion in C++

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?

Upvotes: 3

Views: 3540

Answers (2)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 682

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.

Upvotes: 4

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 8066

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

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

Upvotes: 3

Related Questions