How to implement coordinated iostream formatting?

I would like to limit the amount of formatting of the input / output stream 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 

to base, precision, fill, etc. restored to their previous values โ€‹โ€‹after exiting the block.

Here is the best I came 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 is a rather thorny area, and I'm not sure about the security / relevance of the above. This is dangerous? Have you (or have a third party) already done better?

+4
source share
1 answer

Perhaps something like a Boost I / O stream state library ?

+6
source

All Articles