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
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.
printf("%04d\\n", Num);
should work. Take a look at the printf man page .
printf("%04d", n);
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("%4.4d\n", num);
This article explain what you're trying to do
It is called "padding with leading zeroes"
您使用%04d作为整数的格式字符串。
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.