问题
I just did this
printf( (n==0) ? " %d" : " %3d", n );
but is there a conditional format descriptor?
So, it would mean something like "if this is very short use such and such padding, but, if this is longer use such and such padding."
Can do?
回答1:
There's no conditional, but you can use * to specify the width in the arguments. e.g.:
printf(" %*d", (n==0)?1:3, n);
回答2:
You can pass the field width as an argument using *
:
printf("%*d", length, n);
回答3:
Other answers have pointed out the field width modifier *
.
Since you're comparing for zero/nonzero to determine the length, you can even hack the value of n
into a boolean (1
or 0
), and then multiply that by your desired length:
printf("%*d", !!n*3, n);
来源:https://stackoverflow.com/questions/54577653/is-there-a-branching-string-format-descriptor