【问题标题】:Using hex flag inside setiosflags function在 setiosflags 函数中使用十六进制标志
【发布时间】:2020-09-16 01:14:38
【问题描述】:
int a=60;
cout<<setiosflags(ios::hex|ios::showbase|ios::uppercase);
cout<<a<<endl;

上面的代码不工作,但如果我使用

cout<<hex

然后

cout<<setiosflags(ios::showbase|ios::uppercase)

然后它正在工作

为什么?我怎么知道哪一个可以在 setiosflags() 中使用?

【问题讨论】:

    标签: c++ iomanip


    【解决方案1】:

    您需要先致电resetiosflags,然后再致电setiosflags。原因是 setiosflags(ios::hex|ios::showbase|ios::uppercase) 只是将这些标志附加到流中,就像调用 setf 一样,并且在流中给出了冲突的标志。使用

    std::cout << std::resetiosflags(std::ios_base::dec)
              << std::setiosflags(std::ios::hex|std::ios::showbase|std::ios::uppercase)
              << a << endl;
    

    将使其正确显示a

    【讨论】:

      【解决方案2】:

      第一个版本需要先清除std::ios::dec,否则优先:

      std::cout << resetiosflags (std::ios::dec);
      

      您可以通过使用适当的掩码调用setf 一键完成此操作,例如:

      std.cout.setf (std:ios.hex, std.ios.basefield);
      

      正如cppreference 中所记录的,std::cout &lt;&lt; hex 会为您执行此操作。

      【讨论】:

        猜你喜欢
        • 2019-03-02
        • 2013-06-10
        • 2011-07-15
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        • 2011-12-09
        • 2017-05-07
        • 1970-01-01
        相关资源
        最近更新 更多