我想在 C++ 中限制 I/O 流格式化的效果,这样我就可以做这样的事情:
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
以便在离开块时将基数、精度、填充等恢复到以前的值。
这是我想出的最好的:
#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 (...) {} }
};
...但是 c++ iostreams 是一个相当棘手的领域,我不确定上述内容的安全性/适当性。危险吗?您(或有第三方)已经做得更好了吗?