\n
in scanf
是问题所在
#include<stdio.h>
int main()
{
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d",(marks+i));
}
printf("\nEntered values:\n");
for(i=0;i<3;i++)
{
printf("%d\n",*(marks+i));
}
return 0;
}
Reason:
我只期望3
值存储在数组中,但它存储 4 个值
并在下一个“for”循环中按预期显示 3 个值。我的问题是为什么
在第一个“for”循环中它需要 4 个值而不是 3 个?
First:不,它只存储3
数但不是4
数组中的数字marks[]
.
Second:有趣的是,理解循环只运行三次i = 0
to i < 3
。 for循环根据条件运行。更多有趣的代码被卡在scanf()
如下所述:
Your confusion is why you have to enter four numbers, its not because you loop runs 4
times but its because scanf()
function returns only when you enter a non-space char (and after some enter press you inputs a number symbol that is non-space char).
要了解此行为,请阅读手册:int scanf(const char *format, ...);:
一系列空白字符(空格、制表符、换行符等;请参阅isspace(3)
)。该指令匹配任意数量的空白,
输入中不包括任何内容.
Because in first for loop's, in scanf()
you have included \n
in format string, so scanf()
returns only if press a number enter (or a non-space key).
scanf("%d\n",(marks+i));
^
|
new line char
会发生什么?
假设程序的输入是:
23 <--- because of %d 23 stored in marks[0] as i = 0
<enter> <--- scanf consumes \n, still in first loop
543 <--- scanf returns, and leave 542 unread,
then in next iteration 543 read by scanf in next iteration
<enter>
193
<enter> <--- scanf consumes \n, still in 3rd loop
<enter> <--- scanf consumes \n, still in 3rd loop
123 <--- remain unread in input stream