Museful Museful - 26 days ago 9
C++ Question

Possible to iterate through characters in stringstream without changing its state?

Given a

stringstream ss
, is there a neat way to iterate through the characters currently in it, without changing its state?

Of course, I can
stringstream ss2(ss.str())
and then eat the characters from ss2, but I am hoping there is a way to avoid creating that intermediate string because my
ss
may contain millions of characters.




Background: I encode some data into
ss
, and want to append a CRC before writing it to a disk file. It's for calculating the CRC that I want to iterate through
ss
. The moral thing to do would probably be to subclass
stringstream
and maintain the CRC on the fly, but that feels like too much trouble for my immediate purposes.

Answer

A std::stringstream uses a std::stringbuf as its stream buffer. A std::stringbuf is seekable, like an ordinary file.

You can iterate through the buffered string to your heart's desire, then seek back to the beginning of the buffer, or to some other spot inside the string, and rewind the clock back where it was.