10

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
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
jackhab
  • 17,128
  • 37
  • 99
  • 136

4 Answers4

12

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]);
  • Thanks. Had similar question but I just reconstructed the sstream back than. :( – Muxecoid Feb 12 '09 at 12:38
  • I always thought you needed to call ss.seekg(0, ios::seek_beg) as well as reset the EOF flag -- is that in fact not necessary? I wish the iostreams docs were more precise... – j_random_hacker Feb 13 '09 at 04:27
8

Why are you reading into a temp string variable?

You can just read from the stringstream into an int...

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

    while(ss >> Temp)
        Tokens.push_back(Temp);
}
Assaf Lavie
  • 73,079
  • 34
  • 148
  • 203
7

You have to reset all status flags (eofbit) and bring the stream into a good state (goodbit):

ss.clear(); // clear status flags
ss.str(Tokens[0]);

The reason is that if you keep extracting until the end, you will hit the end, and the eof flag will be set on that stream. After that, read operations will be canceled and you have to clear that flag out again. Anyway, after clearing and resetting the string, you can then go on extracting the integers.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
4

STL! :P

stringstream ss("1 2 3");
vector<int> Tokens;
copy(istream_iterator<int>(ss), istream_iterator<int>(), back_inserter(Tokens));
Logan Capaldo
  • 39,555
  • 5
  • 63
  • 78