Andreas Brinck Andreas Brinck - 1 year ago 138
C++ Question

Equivalent of %02d with std::stringstream?

I want to output an integer to a

with the equivalent format of
. Is there an easier way to achieve this than:

std::stringstream stream;
stream << value;

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

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

Answer Source

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;


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;