c++ - 相当于 %02d 与 std::stringstream?

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

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

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

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

最佳答案

您可以使用 <iomanip> 中的标准操纵器但是没有一个可以同时做到的整洁的fillwidth一次:

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;
}

https://stackoverflow.com/questions/2839592/

相关文章:

javascript - 使用 Javascript 将 24 小时时间转换为 12 小时时间 w/

c# - 您何时使用 StringBuilder.AppendLine/string.Format

c# - DataContractSerializer 创建的 XML 格式

sql - 有哪些免费的 SQL 格式化工具?

string - Scala 中更好的字符串格式

android - 在android中的编辑文本中格式化信用卡

python - 如何很好地格式化dict字符串输出

php - 如何在 PHP 中将数字格式化为美元金额

java - Java 中的 String.format() 和十六进制数字

c# - 使用任意字符串向左或向右填充 string.format(不是 padleft 或 pad