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

泪湿孤枕 提交于 2019-11-29 13:20:44

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.

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!