c++ - 使用 cout << 运算符时,如何用前导零填充 int?

我希望 cout 输出一个带前导零的 int,因此值 1 将打印为 001 和值 25 打印为 025。我该怎么做?

最佳答案

以下,

#include <iomanip>
#include <iostream>

int main()
{
    std::cout << std::setfill('0') << std::setw(5) << 25;
}

输出将是

00025

setfill 默认设置为空格字符(' ')。 setw 设置要打印的字段的宽度,就是这样。


如果您有兴趣了解如何格式化输出流,我为另一个问题写了一个答案,希望它有用: Formatting C++ Console Output.

关于c++ - 使用 cout << 运算符时,如何用前导零填充 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1714515/

相关文章:

bash - 如何在 Bash 中输出粗体文本?

ruby-on-rails - 在ruby中将 Camel 大小写转换为下划线大小写

c# - 自定义数字格式字符串以始终显示符号

c# - 如何在 .NET 中使用自定义格式对 TimeSpan 对象进行 String.Forma

html - 从 XML 中的 html 格式的字符串资源设置 TextView 文本

formatting - 如何更改 Visual Studio Code 中的缩进?

java - 如何在 Java 中打印带有 2 位小数的 float ?

android - 在Android中设置TextView span的颜色

c# - 如何使用 ToString() 格式化可为空的 DateTime?

windows - 在 Windows 批处理脚本中格式化日期和时间