Pregunta

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());
¿Fue útil?

Solución

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()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top