Search code examples
cstring-formatting

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?


Solution

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

    printf(" %*d", (n==0)?1:3, n);