Search code examples
c++stringstream

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?


Solution

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

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