【发布时间】:2015-11-20 12:11:56
【问题描述】:
无法在线找到帮助。有没有办法解决这个问题?
std::showbase 只为非零数字(如here 解释)添加前缀(例如,0x 在std::hex 的情况下)。我想要一个格式为0x0 的输出,而不是0。
但是,仅使用:std::cout << std::hex << "0x" << .... 不是一种选择,因为右侧的参数可能并不总是整数(或等价物)。我正在寻找一个 showbase 替代品,它将在 0 前加上 0x 并且不会扭曲非整数(或等价物),如下所示:
using namespace std;
/* Desired result: */
cout << showbase << hex << "here is 20 in hex: " << 20 << endl; // here is 20 in hex: 0x14
/* Undesired result: */
cout << hex << "0x" << "here is 20 in hex: " << 20 << endl; // 0xhere is 20 in hex: 20
/* Undesired result: */
cout << showbase << hex << "here is 0 in hex: " << 0 << endl; // here is 0 in hex: 0
非常感谢。
【问题讨论】:
-
确实有点奇怪。即使您使用
hex前缀,0仍以 八进制 打印。 :-) Is 0 a decimal literal or an octal literal? -
我不确定我是否理解你的问题,但它是一个 const int& ......事实上它没有打印为
hex,这只是std::showbase的定义,如在我放在 OP 中的链接 -
这是一个内部笑话,根据语法,
0是一个八进制数。即使您以十六进制明确要求它,您也会得到它。 -
这似乎是一个错误?如果您将基数显式设置为 16 (
std::hex),则预计std::showbase将遵守。您刚刚发现了一个将我拖入兔子洞的问题。 -
哦,printf 也会绊倒人...stackoverflow.com/a/14733899/9220132