C ++:根据int值的基数使用条件格式进行打印 [英] C++: Printing with conditional format depending on the base of an int value

查看:91
本文介绍了C ++:根据int值的基数使用条件格式进行打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ;

因为在当前项目中我将不得不做很多次,所以我想知道c ++是否提供了这样的格式说明符.

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.

推荐答案

C ++没有内置这种功能.不过,您可以使用一个简单的包装器来完成此操作:

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;
    }
}

用作cout << large_hex{x}.

如果要使阈值可配置,可以将其设置为large_hex的第二个字段或模板参数(供读者练习).

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).

这篇关于C ++:根据int值的基数使用条件格式进行打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆