代码之家  ›  专栏  ›  技术社区  ›  pilcrow

如何实现作用域iostream格式?

  •  4
  • pilcrow  · 技术社区  · 16 年前

    我想限制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++ iOFFES是一个相当棘手的领域,我不确定上面的安全性和适当性。危险吗?您(或第三方)是否已经做得更好?

    1 回复  |  直到 16 年前
        1
  •  6
  •   C. K. Young    16 年前