Resetting std::stringstream to state before read

Started by
1 comment, last by Juliean 9 years, 2 months ago

Hello,

I need to peek into my stringstream to find out the position of the next occurence of certain characters, like "#". I use std::getline for that, and after that, the stream needs to be reset to its original state:


size_t getCharPosition(std::stringstream& stSourceStream, char c)
{
    const auto position = stSourceStream.tellg();

    std::string stTemp;
    std::getline(stSourceStream, stTemp, c);

    const auto newPosition = stSourceStream.tellg();
    stSourceStream.seekg(position, std::ios::beg);

    return (size_t)newPosition;
}

Now this normally works well, unless c doesn't occur in the stream, in which case after that operation, the stream isn't valid anymore, and I can't read from it again, probably because I read over the end of the stream and some internal flag is set.

Now the question is, what do I have to do additionally to restore the stream correctly? I'd also take a entire different/better method for finding out the next position of a character in the stream. Thanks!

Advertisement
std::basic_ios::clear() should do the trick.

The one time in the standard libary where clear doesn't clear the whole damn thing... thanks :D

This topic is closed to new replies.

Advertisement