71

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;
chema989
  • 3,962
  • 2
  • 20
  • 33
Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
  • 6
    Shouldn't that be `stream.fill('0')` and `stream.width(2)` ? You are using the name of the manipulators almost like you know the answer to your own question? – CB Bailey May 15 '10 at 09:34

6 Answers6

85

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;
}
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
12

You can use

stream<<setfill('0')<<setw(2)<<value;
hpsMouse
  • 2,004
  • 15
  • 20
11

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

stream << boost::format("%|02|")%value;
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
5

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.

vitaut
  • 49,672
  • 25
  • 199
  • 336
0

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;
Arghya Sadhu
  • 41,002
  • 9
  • 78
  • 107
0

I use such function:

#include <stdio.h>
#include <stdarg.h>
#include <cstdio>

const char * sformat(const char * fmt, ...)
{
    static char buffer[4][512]; // nesting less than 4x, length less then 512
    static int i = -1;
    if(++i > 3) i = 0;
    va_list args;
    va_start(args, fmt);
    std::vsnprintf(buffer[i], 511, fmt, args);
    va_end(args);
    return buffer[i];
}