我想用printf
的%02d
格式输出一个整数到std::stringstream
。有没有比这个更简单的方法:
std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;
是否可以将某种格式标志流式传输到stringstream
,例如(伪代码):
stream << flags("%02d") << value;
发布于 2010-05-15 17:29:03
您可以使用来自<iomanip>
的标准操纵器,但是没有一个简洁的操纵器可以同时处理fill
和width
:
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-15 17:29:01
您可以使用
stream<<setfill('0')<<setw(2)<<value;
发布于 2010-05-15 17:29:40
在标准C++中,您不能做得更好。或者,您可以使用Boost.Format:
stream << boost::format("%|02|")%value;
https://stackoverflow.com/questions/2839592
复制相似问题