std :: cout :: setf不起作用(setf为hex)(std::cout::setf doesn't work (setf to hex))

系统教程 行业动态 更新时间:2024-06-14 16:59:17
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: 1023

I 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: 3ff

But, 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: 3ff

Demo on ideone.

更多推荐

本文发布于:2023-04-16 14:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/c70ef1bee8546d69465c6296e7cd2cf1.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   cout   std   setf   work

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!