Equivalent of %02d with std::stringstream?

C++FormattingStringstream

C++ Problem Overview


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;

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

You can use

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

Solution 3 - C++

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

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

Solution 4 - C++

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

Solution 5 - C++

i think you can use c-lick programing.

you can use snprintf

like this

std::stringstream ss;
 char data[3] = {0};
 snprintf(data,3,"%02d",value);
 ss<<data<<std::endl;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndreas BrinckView Question on Stackoverflow
Solution 1 - C++CB BaileyView Answer on Stackoverflow
Solution 2 - C++hpsMouseView Answer on Stackoverflow
Solution 3 - C++Marcelo CantosView Answer on Stackoverflow
Solution 4 - C++vitautView Answer on Stackoverflow
Solution 5 - C++Shangbin DongView Answer on Stackoverflow