c++ - 解决 std::showbase 不加前缀零的问题

标签 c++ c++11 std

无法在线找到帮助。有什么办法可以解决这个问题?

std::showbase只为非零数字添加前缀(例如, 0xstd::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/

相关文章:

c++ - C 中的多位 Trie 实现

c++ - #define NULL nullptr 是否安全?

c++ - std::ostringstream 到 LPCSTR?

c++ - libcurl 如何更改编码 url 行为

C++ 将大量 vector 加倍转换为字符 vector 的最有效方法

c++ - 来自 const std::vector<>& 的自动;对象还是引用?

c++ - 如何重新绑定(bind)自定义分配器?

c++ - 将 void* 转换为 std::function<void()>

c++ - 如何更改 QtCreator 中的 C++ 运行时库设置?

c++ - 命名右值引用