使用std :: stringstream等效%02d?

And*_*nck 58 c++ formatting stringstream

我想输出一个std::stringstream等价格为printf's 的整数%02d.是否有更简单的方法来实现这一点:

std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;
Run Code Online (Sandbox Code Playgroud)

是否有可能将某种格式标志流式传输给stringstream类似(伪代码)的东西:

stream << flags("%02d") << value;
Run Code Online (Sandbox Code Playgroud)

CB *_*ley 73

您可以使用标准的机械手从<iomanip>但没有一个整洁的一个,做两个fillwidth一次:

stream << std::setfill('0') << std::setw(2) << value;
Run Code Online (Sandbox Code Playgroud)

编写自己的对象并不难,当插入到流中时执行两个函数:

stream << myfillandw( '0', 2 ) << value;
Run Code Online (Sandbox Code Playgroud)

例如

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;
}
Run Code Online (Sandbox Code Playgroud)


hps*_*use 9

您可以使用

stream<<setfill('0')<<setw(2)<<value;
Run Code Online (Sandbox Code Playgroud)


Mar*_*tos 9

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

stream << boost::format("%|02|")%value;
Run Code Online (Sandbox Code Playgroud)


vit*_*aut 5

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

不幸的是,标准库不支持将格式说明符作为字符串传递,但您可以使用fmt 库来做到这一点:

std::string result = fmt::format("{:02}", value); // Python syntax
Run Code Online (Sandbox Code Playgroud)

或者

std::string result = fmt::sprintf("%02d", value); // printf syntax
Run Code Online (Sandbox Code Playgroud)

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

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