How to pass parameter n to printf(“%nd”, some_int)

2020-04-02 08:34发布

We all know in C-based languages, printf("%11d", some_int); means right align within an 11 character field, but what if I want to replace this constant 11 here with a dynamic variable, what am I gonna do ?

标签: c linux format
4条回答
欢心
2楼-- · 2020-04-02 09:01

You can use the * character to specify the field width in its own argument:

printf("%*d", some_width, some_int);
查看更多
家丑人穷心不美
3楼-- · 2020-04-02 09:07

use linux command: "man 3 printf" to get more information. One way to do this is

 printf("%*d", width, num);

where width is precision and num is argument to print. Other way equivalent to above one is

 printf("%2$*1$d", width, num);

More generally this is written as "*m$d", where m is int and argument number.

查看更多
闹够了就滚
4楼-- · 2020-04-02 09:07

One way of doing this is to use an snprintf-equivalent on a character array buffer, in order to create your printf format string. (Be sure to check for buffer overflows, of course.)

查看更多
forever°为你锁心
5楼-- · 2020-04-02 09:18

You are going to read the printf(3) man page and come across the following:

Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int.

查看更多
登录 后发表回答