Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterized Leading Zeros in C++ printf function

Tags:

c++

printf

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.

like image 620
Chicoscience Avatar asked Dec 02 '22 22:12

Chicoscience


1 Answers

You can pass a width using *:

printf("%0*d", 5, number);
like image 129
Rafał Rawicki Avatar answered Dec 18 '22 00:12

Rafał Rawicki