70

我想将一个整数输出到 a std::stringstream,其等效格式为printf's %02d。有没有比以下更简单的方法来实现这一点:

std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;

是否可以将某种格式标志流式传输到stringstream,例如(伪代码):

stream << flags("%02d") << value;
4

5 回答 5

83

您可以使用标准的操纵器,<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-15T09:29:02.763 回答
12

您可以使用

stream<<setfill('0')<<setw(2)<<value;
于 2010-05-15T09:29:00.593 回答
11

在标准 C++ 中你不能做得更好。或者,您可以使用 Boost.Format:

stream << boost::format("%|02|")%value;
于 2010-05-15T09:29:39.750 回答
5

是否可以将某种格式标志流式传输到stringstream

不幸的是,标准库不支持将格式说明符作为字符串传递,但您可以使用fmt 库执行此操作:

std::string result = fmt::format("{:02}", value); // Python syntax

或者

std::string result = fmt::sprintf("%02d", value); // printf syntax

你甚至不需要构造std::stringstream. 该format函数将直接返回一个字符串。

免责声明:我是fmt 库的作者。

于 2017-11-24T18:04:25.093 回答
0

我认为你可以使用点击编程。

您可以使用snprintf

像这样

std::stringstream ss;
 char data[3] = {0};
 snprintf(data,3,"%02d",value);
 ss<<data<<std::endl;
于 2020-09-12T11:24:43.803 回答