Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么可以';在第一段代码中,我在数组中输入了五个字符,但是在第二段代码中使用getchar()时,我可以吗?_C_Arrays_Scanf_Getchar - Fatal编程技术网

为什么可以';在第一段代码中,我在数组中输入了五个字符,但是在第二段代码中使用getchar()时,我可以吗?

为什么可以';在第一段代码中,我在数组中输入了五个字符,但是在第二段代码中使用getchar()时,我可以吗?,c,arrays,scanf,getchar,C,Arrays,Scanf,Getchar,如果使用第一个代码,我无法将所有5个字符输入数组。但是如果我使用第二个代码,它就可以工作。为什么? 代码:1 #包括 #包括 int main() { inti,n; chara[5]; 对于(i=0;i原因是当您输入字符时,按enter键。scanf将使用该字符,然后将换行符(\n)保留在标准输入流中(stdin)。下次调用带有%c的scanf时,它会看到换行符保存在stdin中,并直接使用它,因此不会等待进一步的输入 在第二个代码中,getchar()使用上次在每次迭代中调用scanf时留下

如果使用第一个代码,我无法将所有5个字符输入数组。但是如果我使用第二个代码,它就可以工作。为什么?

代码:1
#包括
#包括
int main()
{
inti,n;
chara[5];

对于(i=0;i原因是当您输入字符时,按enter键。
scanf
将使用该字符,然后将换行符(
\n
)保留在标准输入流中(
stdin
)。下次调用带有
%c
scanf
时,它会看到换行符保存在
stdin
中,并直接使用它,因此不会等待进一步的输入

在第二个代码中,
getchar()
使用上次在每次迭代中调用
scanf
时留下的
\n
字符。这就是第二个代码按预期工作的原因

#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;
}
#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;
}