问一个c程序设计(谭浩强)上的题目
这是一个循环输入十个职工的工号和姓名的函数,用一个整型数组储存工号,一个二维字符型数组储存名字,并且两个数组作为参数传给函数
void scan(char n[10][10],int m[10])
{
int i=0;
for(i=0;i<10;i++)
{
printf("please input the number:");
scanf("%d",&m[i]);
printf("please input the name:");
getchar();
gets(n[i]);
}
}
运行出来是这样的:
please input the number:1
please input the name:a
please input the number:2
please input the name:b
please input the number:
如果把上述getchar函数删除那么会出现这种情况
please input the number:1
please input the name:please input the number:2
please input the name:please input the number:3
please input the name:please input the number:4
please input the name:please input the number:
并且我发现,把上述gets函数改为scanf函数就不会出现这种问题
void scan(char n[10][10],int m[10])
{
int i=0;
for(i=0;i<10;i++)
{
printf("please input the number:");
scanf("%d",&m[i]);
printf("please input the name:");
getchar();//删除这一句也是一样的
scanf("%s",n[i]);
}
}
都是这样:
please input the number:1
please input the name:a
please input the number:2
please input the name:b
please input the number:
并且我用putchar(getchar))代替getchar()之后发现getchar()接受到的好像是一个回车
那么为什么这个getchar接收到了一个回车,又为什么把gets换成了scanf后会不一样呢?
【以下回答由 GPT 生成】
在此代码中需要添加getchar
函数来接收回车的原因是因为在使用scanf
函数读取一个整数后,回车键(\n)会留在输入缓冲区中,如果不使用getchar
函数将回车键从缓冲区中读取掉,那么在下一次使用gets
函数读取字符串时,回车键会被当作一个空字符串读入。 若将gets
函数改为scanf
函数后会产生不同的结果是因为scanf
函数在读取字符串时会遇到空格、换行符、制表符等都会停止读取,而gets
函数会读取整行输入,直到遇到换行符为止。因此,使用scanf
函数时需要注意输入的格式和需要读取的内容。如果输入的内容中含有空格或制表符,使用scanf
函数会导致读取不准确的结果。而使用gets
函数则可以正常读取整行输入,不受空格和制表符的影响。此外,gets
函数存在安全性问题,容易造成缓冲区溢出,因此在实际应用中使用fgets
函数更为安全。
【相关推荐】