Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

c++ - Equivalent of %02d with std::stringstream?

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...