Stringstream extract integer

jackhab picture jackhab · Feb 12, 2009 · Viewed 11.9k times · Source

Why do I fail to extract an integer value into the Num variable?

#include <sstream>
#include <vector>
#include <iostream>

using namespace std;

int main()
{
    string Digits("1 2 3");
    stringstream ss(Digits);
    string Temp;
    vector<string>Tokens;

    while(ss >> Temp)
        Tokens.push_back(Temp);

    ss.str(Tokens[0]);

    int Num = 0;
    ss >> Num;
    cout << Num;    //output: 0
}

Answer

anon picture anon · Feb 12, 2009

When the stream extracts the last of the 3 digist "1 2 3" the eof state will be set. This is not cleared by the str() member,you need to do it yourself. Change your code to:

ss.clear();
ss.str(Tokens[0]);