无法在线找到帮助。有什么办法可以解决这个问题?
std::showbase
只为非零数字添加前缀(例如, 0x
在 std::hex
的情况下)(如解释 here )。我想要一个格式化为 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
非常感谢。
最佳答案
尝试
std::cout << "here is 20 in hex: " << "0x" << std::noshowbase << std::hex << 20 << std::endl;
此方式号码将以 0x
为前缀总是,但你必须添加 << "0x"
在打印每个数字之前。
您甚至可以尝试创建自己的流操纵器
struct HexWithZeroTag { } hexwithzero;
inline ostream& operator<<(ostream& out, const HexWithZeroTag&)
{
return out << "0x" << std::noshowbase << std::hex;
}
// usage:
cout << hexwithzero << 20;
保持设置在operator<<
之间打电话,使用来自 here 的答案扩展您自己的流。您将不得不更改语言环境的 do_put
像这样:
const std::ios_base::fmtflags reqFlags = (std::ios_base::showbase | std::ios_base::hex);
iter_type
do_put(iter_type s, ios_base& f, char_type fill, long v) const {
if (v == 0 && ((f.flags() & reqFlags) == reqFlags)) {
*(s++) = '0';
*(s++) = 'x';
}
return num_put<char>::do_put(s, f, fill, v);
}
完整的工作解决方案:http://ideone.com/VGclTi
关于c++ - 解决 std::showbase 不加前缀零的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32226884/