scanf 中的\n 是问题
#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;
}
原因:
我希望只有 3 值存储在数组中,但它存储 4 个值
并在下一个“for”循环中按预期显示 3 个值。我的问题是为什么
在第一个“for”循环中,它需要 4 个值而不是 3 个?
第一:不,它只在数组marks[] 中存储3 数字而不是4 数字。
第二次:有趣的是,i = 0 到 i < 3 的循环只运行了 3 次。 for 循环根据条件运行。更有趣的代码卡在scanf(),如下所述:
您的困惑是为什么您必须输入四个数字,这不是因为您循环运行 4 次,而是因为 scanf() 函数仅在您输入非空格字符时返回(并且经过一些 enter 按你输入一个非空格字符的数字符号)。
要了解这种行为,请阅读手册:int scanf(const char *format, ...);:
一系列空白字符(空格、制表符、换行符等;参见
isspace(3))。该指令 匹配任意数量的空白,
包括无,在输入中。
因为在第一个 for 循环中,在 scanf() 中,您已将 \n 包含在格式字符串中,因此 scanf() 仅在按数字 enter (或非空格 键)。
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