Couldn't find help online. Is there any way to work around this issue?
std::showbase
only adds a prefix (for example, 0x
in case of std::hex
) for non-zero numbers (as explained here). I want an output formatted with 0x0
, instead of 0
.
However, just using: std::cout << std::hex << "0x" << ....
is not an option, because the right hand side arguments might not always be integers (or equivalents). I am looking for a showbase replacement, which will prefix 0 with 0x
and not distort non-ints (or equivalents), like so:
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
thanks a lot.
try
std::cout << "here is 20 in hex: " << "0x" << std::noshowbase << std::hex << 20 << std::endl;
This way number will be prefixed with 0x
always, but you will have to add << "0x"
before every number printed.
You can even try to create your own stream manipulator
struct HexWithZeroTag { } hexwithzero;
inline ostream& operator<<(ostream& out, const HexWithZeroTag&)
{
return out << "0x" << std::noshowbase << std::hex;
}
// usage:
cout << hexwithzero << 20;
To keep setting between operator<<
call, use answer from here to extend your own stream. You would have to change locale's do_put
like this:
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);
}
Complete working solution: http://ideone.com/VGclTi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With