Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "branching" string format descriptor?

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?

like image 637
Fattie Avatar asked Feb 07 '19 16:02

Fattie


3 Answers

There's no conditional, but you can use * to specify the width in the arguments. e.g.:

printf(" %*d", (n==0)?1:3, n);
like image 192
L. Scott Johnson Avatar answered Nov 09 '22 14:11

L. Scott Johnson


You can pass the field width as an argument using *:

printf("%*d", length, n);
like image 23
dbush Avatar answered Nov 09 '22 13:11

dbush


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);
like image 2
Govind Parmar Avatar answered Nov 09 '22 15:11

Govind Parmar