“Roll-Back” or Undo Any Manipulators Applied To A Stream Without Knowing What The Manipulators Were [duplicate]

Yes.

You can save the state and restore it:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{

    std::ios  state(NULL);
    state.copyfmt(std::cout);

    cout << "Hello" << hex << 42 << "\n";
    // now i want to "roll-back" cout to whatever state it was in
    // before the code above, *without* having to know what modifiers I added to it

  // ... MAGIC HAPPENS! ...

    std::cout.copyfmt(state);
    cout << "This should not be in hex: " << 42 << "\n";
}

If you want to get back to the default state you don’t even need to save the state you can extract it from a temporary object.

std::cout.copyfmt(std::ios(NULL));

Leave a Comment