使用printf逐个打印数字并填充零

3

在C++中,使用printf打印一系列数字,可以通过“for”循环实现:

1
2
...
9
10
11

我从这些数字中创建文件。但是当我使用“ls”列出它们时,我得到了
10
11
1
2
..

因此,我想知道如何打印输出,而不是尝试使用Bash解决问题;

0001
0002
...
0009
0010
0011

等等就是这样

谢谢

8个回答

10
i = 45;
printf("%04i", i);

=>

0045

基本上,0告诉printf要用'0'填充,4是数字计数,'i'是整数的占位符(也可以使用'd')。

有关格式占位符,请参见维基百科


6

如果你正在使用C++,那么为什么要使用printf()

使用cout来完成你的任务。

 #include <iostream>
 #include <iomanip>

 using namespace std;

 int main(int argc, char *argv[])
 {

    for(int i=0; i < 15; i++)
    {
        cout << setfill('0') << setw(4) << i << endl;
    }
    return 0;
 }

这是你的输出样式:

0000
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014

C++来拯救!


5

4
printf("%04d", n);

1

简单情况:

for(int i = 0; i != 13; ++i)
  printf("%*d", 2, i)

为什么要使用 "%*d"?因为您不想硬编码前导数字的数量;它取决于列表中最大的数字。使用 IOStreams,您可以使用 setw(int) 实现相同的灵活性。

1
printf("%4.4d\n", num);

0

0

你可以使用 %04d 作为整数的格式字符串。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接