ostream showbase does not show “0x” for zero value

后端 未结 2 807
梦谈多话
梦谈多话 2020-12-20 14:52

PSPS: (a Pre-scripted Post-script)
It has just come to mind that a more prescient question would have included the notion of: Is this non-display of \

相关标签:
2条回答
  • 2020-12-20 15:06

    I found this on https://bugzilla.redhat.com/show_bug.cgi?id=166735 - this is copy/paste straight from there.

    Doesn't sound like a bug to me. ISO C++98, 22.2.2.2.2/10 says std::showbase means prepending # printf conversion qualifier. 22.2.2.2.2/7 says std::hex means the printf conversion specifier is %x. So the behaviour is IMHO required to be the same as printf ("%#x", 0); But http://www.opengroup.org/onlinepubs/009695399/functions/fprintf.html says: "For x or X conversion specifiers, a non-zero result shall have 0x (or 0X) prefixed to it." The same is in ISO C99, 7.19.6.1(6): "For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it."

    So it sounds like the C++98 standard (by saying 'make it like C's printf("%#x", 0)') requires this goofy behavior you're seeing. The only way to get what you want would be to get rid of the std::showbase and output 0x explicitly. Sorry.

    0 讨论(0)
  • 2020-12-20 15:15

    The fact that std::showbase doesn't have an "0x" when the value is zero is sometimes annoying, but that is how it is defined and there is nothing you can do about it, except:

    std::cout << "0x" << .....
    

    The gap between the "0x" and the rest is fixable, but it is not very easy to guess. Try

    std::cout << std::hex << std::showbase << std::setw(8) << std::setfill('0') << h;
    
    0 讨论(0)
提交回复
热议问题