std :: cout :: setf不起作用(setf为hex)(std::cout::setf doesn't work (setf to hex))
我在“Practical C ++ Programming”一书中测试了代码。 但以下示例并不像书中所说的那样有效。 我错过了什么? 请帮忙。
#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: 1023I tested code in the book "Practical C++ Programming". But following example doesn't work as book says. What am I missing? Please help.
#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); }The expected result was
Dec: 1023 Hex: 3ffBut, I got
Dec: 1023 Dec: 1023最满意答案
你需要使用setf的第二个重载来清除std::ios::basefield掩码的基本标志:
std::cout.setf(std::ios::hex, std::ios::basefield); Dec: 1023 Hex: 3ff在ideone上演示。
You need to use the second overload of setf that clears base flags with the std::ios::basefield mask:
std::cout.setf(std::ios::hex, std::ios::basefield); Dec: 1023 Hex: 3ffDemo on ideone.
更多推荐
发布评论