为什么我不能在第一个代码中将五个字符输入到数组中,但在使用第二个代码中所示的 getchar() 时可以?
Why can't I enter five characters into the array in the first code, but can when using a getchar() as shown in the second code?
如果我使用第一个代码,我无法将所有 5 个字符输入到数组中。但是,如果我使用第二个代码,它就可以工作。为什么?
代码:1
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n;
char a[5];
for(i=0;i<5;i++)
{
printf("%d::",i+1);
scanf("%c",&a[i]); //I can input only 1,3,5 values.
}
printf("Enter:\n");
for(i=0;i<5;i++)
printf("%c",a[i]);
getch();
return 0;
}
代码:2
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n;
char a[5];
for(i=0;i<5;i++)
{
printf("%d::",i+1);
scanf("%c",&a[i]);
getchar();
}
printf("Enter:\n");
for(i=0;i<5;i++)
printf("%c",a[i]);
getch();
return 0;
}
原因是当你输入一个字符时,你按下了Enter键。 scanf
将消耗该字符,然后将换行符 (\n
) 留在标准输入流 (stdin
) 中。下次调用带有 %c
的 scanf
时,它会看到 stdin
中保留的换行符并直接使用它,因此不会等待进一步的输入。
在第二个代码中,getchar()
在每次迭代中消耗前一次调用 scanf
留下的 \n
字符。这就是第二个代码按预期工作的原因。
如果我使用第一个代码,我无法将所有 5 个字符输入到数组中。但是,如果我使用第二个代码,它就可以工作。为什么?
代码:1
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n;
char a[5];
for(i=0;i<5;i++)
{
printf("%d::",i+1);
scanf("%c",&a[i]); //I can input only 1,3,5 values.
}
printf("Enter:\n");
for(i=0;i<5;i++)
printf("%c",a[i]);
getch();
return 0;
}
代码:2
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n;
char a[5];
for(i=0;i<5;i++)
{
printf("%d::",i+1);
scanf("%c",&a[i]);
getchar();
}
printf("Enter:\n");
for(i=0;i<5;i++)
printf("%c",a[i]);
getch();
return 0;
}
原因是当你输入一个字符时,你按下了Enter键。 scanf
将消耗该字符,然后将换行符 (\n
) 留在标准输入流 (stdin
) 中。下次调用带有 %c
的 scanf
时,它会看到 stdin
中保留的换行符并直接使用它,因此不会等待进一步的输入。
在第二个代码中,getchar()
在每次迭代中消耗前一次调用 scanf
留下的 \n
字符。这就是第二个代码按预期工作的原因。