mercredi 26 août 2015

Work around std::showbase not prefixing zeros

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.

Aucun commentaire:

Enregistrer un commentaire