Search code examples
cpaddingzero-padding

Zero-padding a string to a finite length


I would like to add a zero padding to a string to make the string a specific final length. In my specific case I want the string to be of length 6 at the end and be padded with 0's before.

int val = 5;
int val2 = 12;
char* padded_val = "000005";
char* padded_val2 = "000012";

I've seen a lot of answers in C# and not a lot in C, the ones I did see added a padding of a certain length to the start of an int or char but what I want is to add a padding to have a final length of 6.

I'd really appreciate a link if this is a duplicate question.


Solution

  • printf("%06d", val);
    

    The 0 indicates what you are padding with and the 6 shows the length of the integer number.

    If you wish to store the result as a string, you can do as following.

    char padded_val[7] = {0};
    sprintf(padded_val, "%06d", val);