Search code examples
cprintfzero-padding

padding zeros at the beginning of a printf statement C


I need to add 0's to some values.

For example if the number is 14, i want to print out 00014.

but I can't just use %05d because the number of padding I want is stored in a variable.

If the variable is equal to 6, I want to print 000014. If it is equal to 3, I want to print out 014 and so on..

Any quick way to do it?

int length = 5;
int someValue = 14;
printf("%0%d%d",length,someValue);

This also doesn't work.

Thank you.


Solution

  • You can use an asterisk * in the format to tell printf to get the field width from an argument:

    printf("%0*d", length, someValue);
    

    You can also use it for precision.

    See e.g. this printf reference for details.