我在“实用C++编程”一书中测试了代码。
但是下面的例子不能像书中所说的那样工作。
我想念什么?请帮忙。

#include <iostream>

int main() {
    int number = 0x3FF;
    std::cout << "Dec: " << number << '\n';
    std::cout.setf(std::ios::hex);
    std::cout << "Hex: " << number << '\n';

    std::cout.setf(std::ios::dec);
}

预期的结果是
Dec: 1023
Hex: 3ff

但是,我得到了
Dec: 1023
Dec: 1023

最佳答案

您需要使用the second overload of setf 使用std::ios::basefield掩码清除基本标志:

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

Dec: 1023
Hex: 3ff

Demo on ideone.

关于c++ - std::cout::setf不起作用(setf为十六进制),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21810741/

10-11 22:00
查看更多