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;
strstream has been deprecated since C++98, std::stringstream and boost::iostreams::array are the recommended replacements.
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.
Stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str .
std::stringstream::str The first form (1) returns a string object with a copy of the current contents of the stream. The second form (2) sets s as the contents of the stream, discarding any previous contents.
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; }
You can use
stream<<setfill('0')<<setw(2)<<value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With