Is there a “branching” string format descriptor?

别等时光非礼了梦想. 提交于 2019-12-12 11:13:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!