70

std::stringstreamの と同等の形式でprintf整数を に出力したい%02d。これを達成するためのより簡単な方法はありますか:

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

stringstream(疑似コード) のような形式フラグを にストリーミングすることは可能ですか?

stream << flags("%02d") << value;
4

5 に答える 5

83

から標準のマニピュレータを使用できますが、両方を一度に<iomanip>行うきちんとしたマニピュレータはありません。fillwidth

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

ストリームに挿入されたときに両方の機能を実行する独自のオブジェクトを作成することは難しくありません。

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

例えば

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;
}
于 2010-05-15T09:29:02.763 に答える
12

使用できます

stream<<setfill('0')<<setw(2)<<value;
于 2010-05-15T09:29:00.593 に答える
11

標準の C++ では、これ以上のことはできません。または、Boost.Format を使用できます。

stream << boost::format("%|02|")%value;
于 2010-05-15T09:29:39.750 に答える
0

c-lickプログラミングが使えると思います。

あなたが使用することができますsnprintf

このような

std::stringstream ss;
 char data[3] = {0};
 snprintf(data,3,"%02d",value);
 ss<<data<<std::endl;
于 2020-09-12T11:24:43.803 に答える