我想输出一个std::stringstream
的整数,其格式为printf
的{{1}}。是否有更简单的方法来实现这一目标:
%02d
是否可以将某种格式标志流式传输到std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;
,类似于(伪代码):
stringstream
答案 0 :(得分:71)
您可以使用<iomanip>
中的标准操纵符,但没有一个同时同时执行fill
和width
的操纵符:
stream << std::setfill('0') << std::setw(2) << value;
编写自己的对象并不难,当插入到流中时执行两个函数:
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;
}
答案 1 :(得分:9)
您可以使用
stream<<setfill('0')<<setw(2)<<value;
答案 2 :(得分:9)
在标准C ++中你不能做得那么好。或者,您可以使用Boost.Format:
stream << boost::format("%|02|")%value;
答案 3 :(得分:1)
是否可以将某种格式标记流式传输到
stringstream
?
不幸的是,标准库不支持将格式说明符作为字符串传递,但您可以使用fmt library执行此操作:
std::string result = fmt::format("{:02}", value); // Python syntax
或
std::string result = fmt::sprintf("%02d", value); // printf syntax
您甚至不需要构建std::stringstream
。 format
函数将直接返回一个字符串。
免责声明:我是fmt library的作者。
答案 4 :(得分:0)
我认为您可以使用c-lick编程。
您可以使用snprintf
像这样
std::stringstream ss;
char data[3] = {0};
snprintf(data,3,"%02d",value);
ss<<data<<std::endl;