I'd like to scope-limit the effect of I/O stream formatting in C++, so that I can do something like this:
std::cout << std::hex << ...
if (some_condition) {
scoped_iofmt localized(std::cout);
std::cout << std::oct << ...
}
// outside the block, we're now back to hex
so that base, precision, fill, etc. are restored to their previous values upon leaving the block.
Here's the best I've come up with:
#include <ios>
class scoped_iofmt
{
std::ios& io_; // The true stream we shadow
std::ios dummy_; // Dummy stream to hold format information
public:
explicit scoped_iofmt(std::ios& io)
: io_(io), dummy_(0) { dummy_.copyfmt(io_); }
~scoped_iofmt() { try { io_.copyfmt(dummy_); } catch (...) {} }
};
... but c++ iostreams are a rather thorny area, and I'm not sure of the safety/appropriateness of the above. Is it dangerous? Have you (or has a third party) already done better?