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 << ... }
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?
source share