Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 与std::stringstream相当的%02d?_C++_Formatting_Stringstream - Fatal编程技术网

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;