问题
In c++, Is there any format specifier to print an unsigned in different base, depending on its value? A format specifier expressing something like this:
using namespace std;
if(x > 0xF000)
cout << hex << "0x" << x;
else
cout << dec << x ;
Because I will have to do this a lot of times in my current project, I would like to know if c++ provides such a format specifier.
回答1:
There is no such functionality built-in to C++. You can use a simple wrapper to accomplish this, though:
struct large_hex {
unsigned int x;
};
ostream& operator <<(ostream& os, const large_hex& lh) {
if (lh.x > 0xF000) {
return os << "0x" << hex << lh.x << dec;
} else {
return os << lh.x;
}
}
Use as cout << large_hex{x}
.
If you want to make the threshold configurable you could make it a second field of large_hex
or a template parameter (exercise for the reader).
来源:https://stackoverflow.com/questions/58975980/c-printing-with-conditional-format-depending-on-the-base-of-an-int-value