在c ++中,是否有任何格式说明符可根据其值以不同的基数打印无符号?格式说明符表达如下内容:
using namespace std;
if(x > 0xF000)
cout << hex << "0x" << x;
else
cout << dec << x ;
Run Code Online (Sandbox Code Playgroud)
因为在当前项目中我必须做很多次,所以我想知道c ++是否提供了这样的格式说明符。
C ++没有内置此类功能。但是,您可以使用一个简单的包装器来完成此操作:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
用作cout << large_hex{x}。
如果要使阈值可配置,可以将其设置为large_hex或模板参数的第二个字段(供读者使用)。