Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

printf() – how to add leading zeroes + padding

I want to pad a column so it’s 8 characters wide, and make integers left-aligned with at most one leading zero like this:

[00      ]
[01      ]
[07      ]
[11      ]
[14      ]

I know how to add the leading zeroes (printf("%02d\n", integer)) or the padding (printf("%-8d\n", integer)), but I don’t know how to combine the two. Is there an easy way to achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Specify both a minimum field width (8) and the precision (.2), like this:

#include <stdio.h>

int main(void)
{
    int array[] = { 0, 1, 7, 11, 14, 314159 };
    enum { NUM_ARRAY = sizeof(array) / sizeof(array[0]) };

    for (int i = 0; i < NUM_ARRAY; i++)
        printf("[%-8.2d]\n", array[i]);
    return 0;
}

Output (on macOS 12.3):

[00      ]
[01      ]
[07      ]
[11      ]
[14      ]
[314159  ]

This seems to be what you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading