1

I am clearing a std::stringstream the usual way:

std::ostringstream ss;
for(...; ...; ...) {
    ... // Use ss.
    if(some_condition_to_reset_stringstream) {
        ss.str(std::string());
        ss.clear();
    }
    ... // Use ss some more.
}

Unfortunately, this does not clear any sticky manipulators (std::hex, std::setfill, etc.).

Is there some way to reset the entire std::stringstream, including any IO manipulators? Or do I have to manually reset each manipulator individually (hopefully not forgetting any in the process)?

zennehoy
  • 6,405
  • 28
  • 55
  • Just throw away the string stream and construct a new one. – Matteo Italia Jul 01 '15 at 09:39
  • @MatteoItalia The stringstream is used within a parsing loop, and must be reset on certain iterations, but not all. So unfortunately I cannot construct a new one every time. – zennehoy Jul 01 '15 at 09:47
  • 1
    @zennehoy: You could save the initial flags and simply reset them via `std::ostringstream::flags`. Note that you also have to save `::fill`, `::width` and `::precision` if you want to revert all changes. – Zeta Jul 01 '15 at 09:51

1 Answers1

4

Apparently in C++11 it should be possible to swap stringstreams:

if(some_condition_to_reset_stringstream) {
    std::ostringstream().swap(ss);
}

Unfortunately I don't have a compiler that supports this (g++ 4.8.2), so I can't test whether this clears sticky manipulators (I don't see why it should not though, once implemented).

Still looking for an alternative, since my compiler doesn't support it :)

zennehoy
  • 6,405
  • 28
  • 55