问题
In order to determine the size of the column in C language we use %<number>d
.
For instance, I can type %3d
and it will give me a column of width=3.
My problem is that my number after the %
is a variable that I receive, so I need something like %xd
(where x
is the integer variable I received sometime before in my program).
But it's not working.
Is there any other way to do this?
回答1:
You can do this as follows:
printf("%*d", width, value);
From Lee's comment:
You can also use a * for the precision size:
printf("%*.*f", width, precision, value);
回答2:
Just for completeness, wanted to mention that with POSIX-compliant versions of printf() you can also put the actual field width (or precision) value somewhere else in the parameter list and refer to it using the 1-based parameter number followed by a dollar sign:
A field width or precision, or both, may be indicated by an asterisk ‘∗’ or an asterisk followed by one or more decimal digits and a ‘$’ instead of a digit string. In this case, an int argument supplies the field width or precision. A negative field width is treated as a left adjustment flag followed by a positive field width; a negative precision is treated as though it were missing. If a single format directive mixes positional (nn$) and non-positional arguments, the results are undefined.
E.g., printf ( "%1$*d", width, value );
来源:https://stackoverflow.com/questions/7105890/set-variable-text-column-width-in-printf