Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Work around std::showbase not prefixing zeros

Tags:

c++

std

c++11

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.

like image 826
alonbe Avatar asked Aug 26 '15 12:08

alonbe


1 Answers

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

like image 64
Hcorg Avatar answered Nov 18 '22 00:11

Hcorg