4
votes

my question is simple. I want to print integers with a specified amount of leading zeros, using printf. However, the number of leading zeros is decided runtime, not known a priori. How could I do that?

If I knew the number of characters (let's say 5), it would be

printf("%05d", number);

But I don't know if it will be 5.

5

5 Answers

10
votes

You can pass a width using *:

printf("%0*d", 5, number);
5
votes

You can also use

cout << setw(width_) << setfill('0') << integerVariable_;

where width_ is decided at runtime.

2
votes

I belive the asterisk can be used to achieve this on most platforms.

int width = whatever();
printf("%0*d", width, number );
2
votes

The standard solution here would be printf("%.*d", precision, number); in the printf family, in C, the precision formatting field specifies a minimum number of digits to be displayed, defaulting to 1. This is independent of the width, so you can write things like:

printf("%6.3d", 12);    // outputs "   012"
printf("%6.0d",  0);    // outputs "      ", without any 0

For either the width or the precision (or both), you can specify '*', which will cause printf to pick the value up from an argument (pass an int):

printf("%6.*d", 3, 12); // outputs "   012"
printf("%*.3d", 6, 12); // outputs "   012"
printf("%*.*d", 6, 3, 12);  // outputs "   012"

Regretfully, there is no equivalent functionality in ostream: the precision is ignored when outputting an integer. (This is probably because there is no type dependent default for the precision. The default is 6, and it applies to all types which respect it.)

-1
votes

use manipulators available in C++ setw and setfill.