Interview Questions

How can I implement a variable field width with printf?

C Interview Questions and Answers


(Continued from previous question...)

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.

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.)

(Continued on next question...)

Other Interview Questions