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?
There's no conditional, but you can use * to specify the width in the arguments. e.g.:
printf(" %*d", (n==0)?1:3, n);
You can pass the field width as an argument using *
:
printf("%*d", length, n);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With