How can I implement a variable field width with printf?

Q

How can I implement a variable field width with printf? That is, instead of something like %8d, I want the width to be specified at run time.

✍: Guest

A

printf("%*d", width, x) will do just what you want. The asterisk in the format specifier indicates that an int value from the argument list will be used for the field width. (Note that in the argument list, the width precedes the value to be printed.)

2021-01-21, 6447👍, 1💬