Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 
like image 797
Andreas Brinck Avatar asked May 15 '10 09:05

Andreas Brinck


People also ask

Is Stringstream deprecated?

strstream has been deprecated since C++98, std::stringstream and boost::iostreams::array are the recommended replacements.

What should I use for Stringstream?

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.

What is std :: Stringstream?

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 .

What does Stringstream return in C++?

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.


2 Answers

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; } 
like image 147
CB Bailey Avatar answered Sep 21 '22 10:09

CB Bailey


You can use

stream<<setfill('0')<<setw(2)<<value; 
like image 26
hpsMouse Avatar answered Sep 24 '22 10:09

hpsMouse