`printf` 中的 %*c%*c 是什么?

What is %*c%*c in `printf`?

当我在 printf 中使用 %*c%*c 中的 printf 时,它需要 4 个值,并且还打印 4 和 5 的总和。我找不到有效的理由。

研究的时候发现%*c表示宽度。但是什么是宽度以及下面示例的总和是如何导出的?

printf("%*c%*c", 4, ' ', 5, ' ');

Ideone link

代码:

#include <stdio.h>

int add(int x, int y)
{
    return printf("%*c%*c",x,' ', y,' ');
}

int main()
{
    printf("%d",add(4,5));
    return 0;
}

printf returns打印的字符数。

printf("%*c", N, C); 打印 N-1 个空格后跟字符 C.

更一般地说,printf 打印 N - length_of_text 个空格(如果该数字为 > 0,否则为零空格),然后是文本。这同样适用于数字。

因此

return printf("%*c%*c", x, ' ', y, ' ');

打印前缀为 x 的 space 减去 length_of_space 其他 spaces (x-1),然后对 y 做同样的事情.这使得 4+5 spaces 在你的情况下。然后printfreturns打印的总字符数,9.

printf("%d",add(4,5));

这个 printf 打印 add() 函数返回的整数 9.

默认情况下,printf 是右对齐的(文本前有空格)。要使其对齐,

  • 给出负数N,或者
  • *前加一个-,例如%-*s,或
  • 静态版本也可以,例如%-12s%-6d

printf("%*c%*c", 4, ' ', 5, ' '); 在大小为 4 的字段中打印 space,然后在大小为 5 的字段中打印 space。因此总共有 9 个字符。

在您发布的代码中,函数 returns printf 的结果给出了打印的字符数,因此 9。然后主要打印此数字 9。

一切如期而至。根据 manual

format
(optional) . followed by integer number or *, or neither that specifies precision of the conversion. In the case when * is used, the precision is specified by an additional argument of type int. If the value of this argument is negative, it is ignored. If neither a number nor * is used, the precision is taken as zero. See the table below for exact effects of precision.

Return value
1-2) Number of characters written if successful or negative value if an error occurred.

所以在你的情况下:

int add(int x, int y)
{
    return printf("%*c%*c",x,' ', y,' ');
    //              ^ x is for the first *, y for the second *
}

结果写了space的x + y个数(包括精度),也就是return的值。