我想将一个整数输出到 a std::stringstream
,其等效格式为printf
's %02d
。有没有比以下更简单的方法来实现这一点:
std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;
是否可以将某种格式标志流式传输到stringstream
,例如(伪代码):
stream << flags("%02d") << value;
我想将一个整数输出到 a std::stringstream
,其等效格式为printf
's %02d
。有没有比以下更简单的方法来实现这一点:
std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;
是否可以将某种格式标志流式传输到stringstream
,例如(伪代码):
stream << flags("%02d") << value;
您可以使用标准的操纵器,<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;
}
您可以使用
stream<<setfill('0')<<setw(2)<<value;
在标准 C++ 中你不能做得更好。或者,您可以使用 Boost.Format:
stream << boost::format("%|02|")%value;
是否可以将某种格式标志流式传输到
stringstream
?
不幸的是,标准库不支持将格式说明符作为字符串传递,但您可以使用fmt 库执行此操作:
std::string result = fmt::format("{:02}", value); // Python syntax
或者
std::string result = fmt::sprintf("%02d", value); // printf syntax
你甚至不需要构造std::stringstream
. 该format
函数将直接返回一个字符串。
免责声明:我是fmt 库的作者。
我认为你可以使用点击编程。
您可以使用snprintf
像这样
std::stringstream ss;
char data[3] = {0};
snprintf(data,3,"%02d",value);
ss<<data<<std::endl;