%n
格式说明符,当在 a 中使用时,应将scanf()
函数已处理的格式字符串的字符数存储到类型的参数中int*
。根据定义:
The number of characters of the format string already processed is stored in the pointed location.
但是在我的程序中,除了第一个之外,它scanf()
在所有scanf()
s 中都有效。在我的程序中的所有 s 中,不包括第一个,它存储从控制台输入的字符总数的计数,包括换行符(Enter键)。但是在第一个scanf()
中,计数 比从控制台输入的字符和换行符的总数少一。
请解释这个异常,因为我无法检测到这个简单的错误真的很令人沮丧。
#include <stdio.h>
int main ()
{
int a,b,c,d,count;
printf("First Trial\n");
scanf("%d%d%d%d%n",&a,&b,&c,&d,&count); //OUTPUT ANOMALY HERE
printf("count=%d\n",count);
printf("Second Trial\n");
scanf("%d%n",&a,&count);
printf("count=%d\n",count);
printf("Third Trial\n");
scanf("%d%d%n",&a,&b,&count);
printf("count=%d\n",count);
printf("Fourth Trial\n");
scanf("%d%n%d",&a,&count,&b);
printf("count=%d",count);
}
样本输出
First Trial
253
34
4
83
count=11
Second Trial
25
count=3
Third Trial
234
38
count=7
Fourth Trial
3534
35
count=5
为什么在第一次试验中我们得到“11”而不是“12”?这是我的疑问。
关键编辑
另一个发现。如果是第一个scanf()
,而不是使用Enter
键(换行符)来分隔输入的数字,如果我使用空格,很多空格,那么所有这些空格也会被计算在内。count
例如,我得到count=21
。这意味着换行符,空间,一切都在考虑之中。但为什么一审少一个?
First Trial
25 35 38 98
count=21