Equivalent of %02d with std::stringstream?

蓝咒 提交于 2019-11-27 12:38:57

问题


I want to output an integer to a std::stringstream with the equivalent format of printf's %02d. Is there an easier way to achieve this than:

std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;

Is it possible to stream some sort of format flags to the stringstream, something like (pseudocode):

stream << flags("%02d") << value;

回答1:


You can use the standard manipulators from <iomanip> but there isn't a neat one that does both fill and width at once:

stream << std::setfill('0') << std::setw(2) << value;

It wouldn't be hard to write your own object that when inserted into the stream performed both functions:

stream << myfillandw( '0', 2 ) << value;

E.g.

struct myfillandw
{
    myfillandw( char f, int w )
        : fill(f), width(w) {}

    char fill;
    int width;
};

std::ostream& operator<<( std::ostream& o, const myfillandw& a )
{
    o.fill( a.fill );
    o.width( a.width );
    return o;
}



回答2:


You can use

stream<<setfill('0')<<setw(2)<<value;



回答3:


You can't do that much better in standard C++. Alternatively, you can use Boost.Format:

stream << boost::format("%|02|")%value;



回答4:


Is it possible to stream some sort of format flags to the stringstream?

Unfortunately the standard library doesn't support passing format specifiers as a string, but you can do this with the fmt library:

std::string result = fmt::format("{:02}", value); // Python syntax

or

std::string result = fmt::sprintf("%02d", value); // printf syntax

You don't even need to construct std::stringstream. The format function will return a string directly.

Disclaimer: I'm the author of the fmt library.



来源:https://stackoverflow.com/questions/2839592/equivalent-of-02d-with-stdstringstream

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