【问题标题】:Why cout<<hex satement makes the rest print in hex format only为什么 cout<<hex 语句只以十六进制格式打印其余部分
【发布时间】:2014-05-21 12:57:59
【问题描述】:

我有以下代码 sn-ps 来打印整数的十六进制值,

int i=10;
cout<<hex<<i<<endl;

在控制台上打印十六进制值 10 a

但是在下一行我需要打印另一个变量的十进制值,比如

  int j=11;
  cout<<j<<endl;

但它也会打印十六进制值 11,b,如果我使用 cout&lt;&lt;dec&lt;&lt;j&lt;&lt;endl;,它会打印十进制值。

我还注意到,如果之前使用过cout&lt;&lt;hex,所有cout 都会打印变量的十六进制值。

所以我的问题是正常行为吗?如果我之前使用过一次&lt;&lt;hex,是否需要使用&lt;&lt;dec

【问题讨论】:

  • 是的,如果你想切换它,我相信你必须做&lt;&lt;dec&lt;&lt;hex。如果我没记错的话,你正在做的是设置一个标志以十六进制或十进制打印,它会保留该标志,直到它被设置为其他东西。
  • 是的,您必须将其重置为 std::dec(技术上清除 std::ios_base::basefield 位掩码,该位掩码仍将设置 std::ios_base::hex 的位。

标签: c++ hex cout


【解决方案1】:

是的,您必须使用dec 才能使用cout 十进制值,因为hex 是一个“粘性”操纵器(顺便说一句,就像许多其他操纵器一样)- 它会一直存在直到更改。

【讨论】:

    【解决方案2】:

    cout 是一个全局变量。操纵器中的移动会修改该全局的状态。鉴于您可以将操纵器链接在一起,cout 的实例永远不会知道何时“取消设置”它。所以,它仍然存在。

    【讨论】:

      【解决方案3】:

      您可以编写自己的操纵器来克服“粘性”行为:

      #include <iostream>
      #include <iomanip>
      #include <limits>
      
      // Hex
      // ============================================================================
      
      template <typename T>
      struct Hex
      {
          enum { Width = (std::numeric_limits<T>::digits + 1) / 4 };
          const T& value;
          const int width;
      
          Hex(const T& value, int width = Width)
          : value(value), width(width)
          {}
      
          void write(std::ostream& stream) const {
              if(std::numeric_limits<T>::radix != 2) stream << value;
              else {
                  std::ios_base::fmtflags flags = stream.setf(
                      std::ios_base::hex, std::ios_base::basefield);
                  char fill = stream.fill('0');
                  stream << "0x" << std::setw(width) << value;
                  stream.fill(fill);
                  stream.setf(flags, std::ios_base::basefield);
              }
          }
      };
      
      template <typename T>
      inline Hex<T> hex(const T& value, int width = Hex<T>::Width) {
          return Hex<T>(value, width);
      }
      
      template <typename T>
      inline std::ostream& operator << (std::ostream& stream, const Hex<T>& value) {
          value.write(stream);
          return stream;
      }
      
      
      int main()
      {
          unsigned short i = 0xa;
          std::cout << hex(i) << " == " << i << '\n';
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-01-11
        • 2013-03-31
        • 2020-05-14
        • 1970-01-01
        • 1970-01-01
        • 2020-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多