【问题标题】:Work around std::showbase not prefixing zeros解决 std::showbase 不添加零前缀的问题
【发布时间】:2015-11-20 12:11:56
【问题描述】:

无法在线找到帮助。有没有办法解决这个问题?

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

标签: c++ c++11 std


【解决方案1】:

试试

std::cout << "here is 20 in hex: " << "0x" << std::noshowbase << std::hex << 20 << std::endl;

这种方式号码将始终以0x 为前缀,但您必须在打印每个号码之前添加&lt;&lt; "0x"

您甚至可以尝试创建自己的流操纵器

struct HexWithZeroTag { } hexwithzero;
inline ostream& operator<<(ostream& out, const HexWithZeroTag&)
{
  return out << "0x" << std::noshowbase << std::hex;
}

// usage:
cout << hexwithzero << 20;

要在operator&lt;&lt; 呼叫之间保持设置,请使用来自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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多