Sign in to follow this  
Juliean

Resetting std::stringstream to state before read

Recommended Posts

Juliean    7077

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!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this