ron zamir
ron zamir

Reputation: 23

How to fill a number with a variable amount of 0s?

I'm trying to print a number with a certain amount of zeros before it. I know that in order to print a constant amount of zeros I need to

printf("%05d", num);

But how can I print a varying amount of zeros? Let's say that the amount will be int spacing.

Upvotes: 0

Views: 226

Answers (1)

abelenky
abelenky

Reputation: 64682

#include <stdio.h>

int main(void) {
    int alpha = 1;
    int beta = 23456;
    int spacing = 3;

    printf("Alpha: %0*d\n", spacing, alpha);

    spacing = 8;
    printf("Beta:  %0*d\n", spacing, beta);
    return 0;
}

Example output:

Success #stdin #stdout 0s 4372KB
Alpha: 001
Beta:  00023456

Upvotes: 3

Related Questions