tags:

views:

164

answers:

8

Hi,

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 using bash, I wonder how could I print;

0001
0002
...
0009
0010
0011

and so on

Thanks

+4  A: 

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

Aidan Cully
A: 

This article explain what you're trying to do

It is called "padding with leading zeroes"

Eric
+1  A: 
printf("%4.4d\n", num);
Jerry Coffin
+1 for the only solution that uses the precision flag
John Dibling
+3  A: 
printf("%04d", n);
Stephen Chu
+7  A: 
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.

schnaader
A: 

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

Noah Roberts
+1  A: 

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!

srikfreak
+1 for being the only answer to use idiomatic C++.
Johnsyweb
A: 

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)

MSalters