2

I have an stringstream, pushing to it in an iteration. After casting its content to an int object, it never changes after that. I think it changes but instance.str() is pointing to an invalidated place in which the string is not there anymore.

bool h = 1;
stringstream ss;
for(int i = 0; i < input.length(); i++)
{
    if(input[i] != ':')
    {
        cout << "input:  " << input[i] << endl;
        ss << input[i];
        cout << "ss:  " << ss.str() << endl;
    }
    else
        if(h)
        {
            ss >> hour;
            ss.str(string());
            h = 0;
        }   
}

in this loop, after the satisfaction of the condition( h being true), the stream's content is casting to an int. till this moment everything works fine but after this moment, ss.str() returns an empty string.

was my guess about invalidated string pointer right? if yes, what is the reason? if no, what is the reason of this behavior?

UPDATE: I changed the sources code because the previous version was the way I handled the issue by this trick:

stringstream a(ss.str());
a >> hour;
ss.str(string());
Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
Pooya
  • 992
  • 2
  • 10
  • 31
  • Why do you have that addtitional `string()` in the second to last line? – niklasfi Apr 18 '14 at 08:31
  • @niklasfi to clear the content. – Pooya Apr 18 '14 at 08:32
  • Maybe this solves your problem: http://stackoverflow.com/questions/7623650/resetting-a-stringstream . Anyway, you should post a compilable piece of code. Maybe your error comes from somewhere else. – Rémi Apr 18 '14 at 08:36
  • @Rémi yeah, that solved the problem. tnx. but I was curious about the reason. – Pooya Apr 18 '14 at 08:41
  • I added an answer. You can also check that question: http://stackoverflow.com/questions/20731/in-c-how-do-you-clear-a-stringstream-variable – Rémi Apr 18 '14 at 09:10

1 Answers1

2

The problem is that this line:

ss >> hour;

sets the eof bit of your stream because you reached the end of the string. When the eof bit is set, then the stream does not work any more. So you have to clear it after setting the empty string:

ss.str(string())
ss.clear()
Rémi
  • 3,705
  • 1
  • 28
  • 39