Equivalent to% 02d with std :: stringstream?

I want to print an integer in std::stringstream with the equivalent printf %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 pass format streams to stringstream , something like (pseudocode):

 stream << flags("%02d") << value; 
+47
c ++ formatting stringstream
May 15 '10 at 9:21 a.m.
source share
4 answers

You can use standard manipulators from <iomanip> , but there is no clear one that does fill and width at the same time:

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

It is easy to write your own object so that when you insert into the stream, both functions are performed:

 stream << myfillandw( '0', 2 ) << value; 

eg.

 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; } 
+59
May 15 '10 at 9:29 a.m.
source share

You cannot do it much better in standard C ++. Alternatively, you can use Boost.Format:

 stream << boost::format("%|02|")%value; 
+9
May 15 '10 at 9:29 a.m.
source share

you can use

 stream<<setfill('0')<<setw(2)<<value; 
+8
May 15 '10 at 9:29 a.m.
source share

Is it possible to transfer format streams to stringstream ?

Unfortunately, the standard library does not 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 build std::stringstream . The format function will return a string directly.

Disclaimer I am the author of fmt library .

0
Nov 24 '17 at 18:04
source share



All Articles