printf with leading zeros

Jun 12, 2012 at 10:30pm
Hi all,

1
2
int i = 1;
printf("%05d", i);

should output "00001". That's fine. However, I am wondering whether there is any way to determine the total number of digits (5 in this example) dynamically during program run-time? It should equal the number of digits (call it max_digits) of the largest number within an integer array, which is not known a priori.

Thanks a lot,

Rudey
Jun 12, 2012 at 10:50pm
You have two possibilities. The first is that you can generate the format string yourself. The second is that you can use '*' and specify required number of digits as a parameter of printf. For example

std::printf( "%0*d", 3, i );

Here 3 is the number of digiits.
Last edited on Jun 12, 2012 at 11:04pm
Jun 12, 2012 at 10:56pm
Thanks a lot! That will solve my problem.
Topic archived. No new replies allowed.