开发者

Print numbers sequentially using printf with filling zeroes

in C++, using printf I want to print a sequence of number, so I get, from a "for" loop;

1
2
...
9
10
11

and I create files from those numbers. But when I list them using "ls" I get

10
11
1
2
..

so instead of trying to solve the problem us开发者_如何学JAVAing bash, I wonder how could I print;

0001
0002
...
0009
0010
0011

and so on

Thanks


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

=>

0045

Basically, 0 tells printf to fill with '0', 4 is the digit count and 'i' is the placeholder for the integer (you can also use 'd').

See Wikipedia about the format placeholders.


If you are using C++, then why are you using printf()?

Use cout to do your job.

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

And this is how your output will look:


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

C++ to the rescue!


printf("%04d\n", Num); should work. Take a look at the printf man page.


printf("%04d", n);


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


Simple case:

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

Why "%*d" ? Because you don't want to hardcode the number of leading digits; it depends on the largest number in the list. With IOStreams, you have the same flexibility with setw(int)


This article explain what you're trying to do

It is called "padding with leading zeroes"


You use %04d as your format string for the integer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜