转换说明符 %n 究竟做了什么?

What does conversion specifier %n exactly do?

我刚刚在查看标准时遇到了这个问题:

7.19.6.1 The fprintf function

8 The conversion specifiers and their meanings are:

关于:

n The argument shall be a pointer to signed integer into which is written the number of characters written to the output stream so far by this call to fprintf. No argument is converted, but one is consumed. If the conversion specification includes any flags, a field width, or a precision, the behavior is undefined.

这是什么意思? %n 是做什么的?

我没看错吗,根据:

Returns

14 The fprintf function returns the number of characters transmitted

在此代码段中:

int a, b;
b = printf ("Thi%n\s is just a test",&a);

a 等于 b?

the number of characters written to the output stream so far

"So far",意思是无论你把%n放在哪里,结果都会改变。对于您的示例,它将是 3.

如果您将 %s 位置增加一个字符,指向的结果变量将增加一个。将 %s 放在字符串的末尾将使它等于 printf

返回的值

a = 3 和 b = 19 适合你的情况

a 将等于 %n 之前打印的字符数。 假设您尝试打印 printf ("This%sis%n just a test","coder", &a); 那么a的值就是this + coder + is = 11.

而b的值始终是打印的字符总数