STD :: Ostream忽略了通过setf()在基础上设置的十六进制标志

std::ostream ignores hex flag set on the underlying via setf()

本文关键字:基础上 设置 标志 十六进制 setf Ostream STD      更新时间:2023-10-16

以下C 代码令人惊讶地产生小数输出,显然忽略了对setf()的调用和打印true 42。使用std::setiosflags()给出相同的结果。但是,使用std::cout << std::hex确实给出了预期的输出true 0x2a,因此std::ios::showbasestd::ios::boolalpha得到了尊重。

我已经在Ubuntu上测试了G 5.4和CentOS上的G 7.2.1。我在这里缺少什么?

#include <sstream>
#include <iostream>
#include <iomanip> 
#include <iterator>
int main()
{
    std::cout.setf(std::ios::hex | std::ios::showbase | std::ios::boolalpha);
    // Uncommenting the line below doesn't make a difference.
    //std::cout << std::setiosflags(std::ios::hex | std::ios::showbase | std::ios::boolalpha);
    // Uncommenting this line does give the desired hex output.
    //std::cout << std::hex;
    int m = 42;
    std::cout << true << ' ' << m << std::endl;
    return 0;
}

setf的这种变体仅添加 flags,但您需要清除基本字段。

因此,您需要使用口罩的过载:

    std::cout.setf(std::ios::hex | std::ios::showbase | std::ios::boolalpha,
                   std::ios_base::basefield | std::ios::showbase | std::ios::boolalpha);

输出:

true 0x2a

live demo