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;
You can use the standard manipulators from
<iomanip>
but there isn't a neat one that does bothfill
andwidth
at once:It wouldn't be hard to write your own object that when inserted into the stream performed both functions:
E.g.
You can't do that much better in standard C++. Alternatively, you can use Boost.Format:
Unfortunately the standard library doesn't support passing format specifiers as a string, but you can do this with the fmt library:
or
You don't even need to construct
std::stringstream
. Theformat
function will return a string directly.Disclaimer: I'm the author of the fmt library.
You can use