无法在线寻求帮助.有没有办法解决这个问题?
std::showbase仅增加了一个前缀(例如,0x在以下情况下std::hex)为非零数(如所解释这里).我想要一个格式化的输出0x0,而不是0.
但是,仅使用:std::cout << std::hex << "0x" << ....不是一个选项,因为右侧参数可能并不总是整数(或等价物).我正在寻找一个showbase替换,它将前缀为0 0x而不是扭曲非int(或等价物),如下所示:
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
Run Code Online (Sandbox Code Playgroud)
非常感谢.
尝试
std::cout << "here is 20 in hex: " << "0x" << std::noshowbase << std::hex << 20 << std::endl;
Run Code Online (Sandbox Code Playgroud)
这样,数字将以0x“always”为前缀,但您必须<< "0x"在打印的每个数字之前添加。
您甚至可以尝试创建自己的流操纵器
struct HexWithZeroTag { } hexwithzero;
inline ostream& operator<<(ostream& out, const HexWithZeroTag&)
{
return out << "0x" << std::noshowbase << std::hex;
}
// usage:
cout << hexwithzero << 20;
Run Code Online (Sandbox Code Playgroud)
要在operator<<通话之间保持设置,请使用此处的应答来扩展您自己的流。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);
}
Run Code Online (Sandbox Code Playgroud)
完整的工作解决方案:http://ideone.com/VGclTi
| 归档时间: |
|
| 查看次数: |
607 次 |
| 最近记录: |