C++ 与std::stringstream相当的%02d?
我想用C++ 与std::stringstream相当的%02d?,c++,formatting,stringstream,C++,Formatting,Stringstream,我想用printf的%02d的等效格式将一个整数输出到std::stringstream。有没有比以下更简单的方法来实现这一点: std::stringstream stream; stream.setfill('0'); stream.setw(2); stream << value; 你可以用 stream<<setfill('0')<<setw(2)<<value; stream您可以使用中的标准操纵器,但是没有一个整洁的操纵器可以同时执
printf
的%02d
的等效格式将一个整数输出到std::stringstream
。有没有比以下更简单的方法来实现这一点:
std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;
你可以用
stream<<setfill('0')<<setw(2)<<value;
stream您可以使用
中的标准操纵器,但是没有一个整洁的操纵器可以同时执行填充
和宽度
:
stream << std::setfill('0') << std::setw(2) << value;
<代码>流> p>在标准C++中你不能做得更好。或者,您可以使用Boost.Format:
stream << boost::format("%|02|")%value;
流
是否可以将某种格式标志流式传输到stringstream
不幸的是,标准库不支持将格式说明符作为字符串传递,但您可以通过以下方法来实现:
或
您甚至不需要构造std::stringstream
。format
函数将直接返回字符串
免责声明:我是。的作者,我认为您可以使用c-lick编程
您可以使用snprintf
像这样
std::stringstream ss;
char data[3] = {0};
snprintf(data,3,"%02d",value);
ss<<data<<std::endl;
std::stringstream-ss;
字符数据[3]={0};
snprintf(数据,3,“%02d”,值);
那不应该是stream.fill('0')
和stream.width(2)
?你正在使用操纵器的名称,就像你知道自己问题的答案一样?如果你没有将流
用于其他任何事情,你就不需要它,因为boost::format
已经生成了一个字符串。我听说你必须将它传递给str(…)
thenJahonnes你可以使用std::string myStr=(boost::format(“%| 02 |”)%value.str();
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 << boost::format("%|02|")%value;
std::string result = fmt::format("{:02}", value); // Python syntax
std::string result = fmt::sprintf("%02d", value); // printf syntax
std::stringstream ss;
char data[3] = {0};
snprintf(data,3,"%02d",value);
ss<<data<<std::endl;