Museful Museful - 1 year ago 67
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
may contain millions of characters.

Background: I encode some data into
, 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
. The moral thing to do would probably be to subclass
and maintain the CRC on the fly, but that feels like too much trouble for my immediate purposes.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download