JP van Oosten

istringstream::str not resetting eof

Oct 27, 2008

Today I was implementing a c++-function which read single words from a file. Because the first few characters of each line needed to be stripped, I could not use simple string extraction from the filestream. This lead me to use the istringstream.

Unfortunately, the istringstream gave me a minor problem: it only seemed to extract words for the first line in each file!

Because I wanted to reuse a single stream, I used the istringstream:: str(string const &text) method to fill the stream with the current line's content. From there I used the string extraction.

After a bit, I remembered I had seen this problem before, and remembered I needed to reset something. After a bit of digging, I found out that when the extraction reached the end of the string, the eof-bit would be set. Filling the stream with new data using the str method, did not reset these bits, unfortunately.

The fix was then easy: istringstream::clear() does the job.