C语言输入员工人数后gets未等待输入直接输出Name == name is的原因
问题原因及解决方法
根因分析
scanf("%d", &people)只会读取输入的整数值,你输入完数字按下的换行符会残留在输入缓冲区中。后续第一次调用gets()时,会直接把这个残留的换行符当成一次有效输入,读取到空内容,所以程序看起来没有等待你输入姓名就直接输出了结果。- 额外补充:
gets()是C语言标准中已经被废弃的函数,没有边界检查逻辑,输入内容超过数组长度时会触发缓冲区溢出,存在严重安全隐患,禁止在生产代码中使用。
修复方案
首先清理scanf残留的换行符,同时把gets()替换为安全的fgets()函数,修改后的代码如下:
#include<stdio.h> #include<string.h> struct employee{ char name[40]; char company[40]; int age; }; int main(){ int people; printf("How many peoplees data is being entered : "); scanf("%d",&people); // 清理输入缓冲区残留的换行符 while(getchar() != '\n'); struct employee credentials[people]; for(int count=0;count<people;count++){ printf("Name == "); // fgets指定读取长度,避免缓冲区溢出 fgets(credentials[count].name, sizeof(credentials[count].name), stdin); // 去除fgets读取到的末尾换行符 credentials[count].name[strcspn(credentials[count].name, "\n")] = '\0'; printf("name is %s\n\n",credentials[count].name); } return 0; }
内容的提问来源于stack exchange,提问作者ashhad siddiqui
相关产品推荐
相关产品推荐

