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

两盒软妹~` 提交于 2019-12-13 20:13:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!