# Resetting std::stringstream to state before read

## Recommended Posts

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 on other sites
std::basic_ios::clear() should do the trick.

##### Share on other sites

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

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628298
• Total Posts
2981890

• 9
• 9
• 11
• 10
• 10