c语言为什么这里要加一个getchar函数

问一个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函数更为安全。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
  1. scanf遇到空格或者回车才会停止,而我们每次输完后按的回车其实也会和你所输入的一起输入到里面作为终止
  2. 在我们输入的过程中,还有一个东西叫做缓冲区buffer,我们从键盘上输入的数据会先放到buffer里然后才被scanf获取,当遇到回车时就会停止,而这个回车仍然在缓冲区里面
  3. 所以getchar是用来吧这个回车取出来的,防止回车的影响
  4. 而gets会吧回车读就去,而scanf会自动跳过一开始的空格和回车读到真正的数据