gpt4 book ai didi

c++ - std::ostream 忽略通过 setf() 在底层设置的十六进制标志

转载 作者:行者123 更新时间:2023-11-28 04:48:50 25 4
gpt4 key购买 nike

下面的 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 的变体仅添加 标志,但您需要清除基字段。

所以你需要使用带掩码的重载:

    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

关于c++ - std::ostream 忽略通过 setf() 在底层设置的十六进制标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48627004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com