C++:根据 int 值的基数以条件格式打印

C++: Printing with conditional format depending on the base of an int value

在 c++ 中,是否有任何格式说明符可以根据其值以不同的基数打印无符号数?表达如下内容的格式说明符:

using namespace std; 
if(x > 0xF000) 
   cout << hex << "0x" << x;
else 
   cout << dec << x ;

因为在我现在的项目中我会经常这样做,所以我想知道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;
    }
}

用作cout << large_hex{x}

如果您想使阈值可配置,您可以将其设为 large_hex 的第二个字段或模板参数(reader 的练习)。