循环第二次迭代时fgets()函数无法获取输入的技术求助
解决C程序输入学生信息时姓名输入被跳过的问题
你的程序在第二次输入学生姓名时直接跳过,核心原因是**scanf读取整数后,输入缓冲区里残留的换行符被后续输入函数直接读取**,再加上gets函数本身存在缓冲区溢出风险,早已被C标准废弃,这两个问题叠加导致了异常。
解决思路及修改步骤
- 替换不安全的
gets为fgets:fgets支持指定最大读取长度,能避免缓冲区溢出,同时兼容多单词输入。 - 清理
scanf后的缓冲区残留:每次用scanf读取学号后,把缓冲区里剩下的换行符(或其他多余字符)清空,避免干扰下一次输入。 - 去除
fgets读取的换行符:fgets会把用户输入的换行符也存入数组,需要替换为字符串结束符'\0',避免输出异常。
修改后的完整代码
#include <stdio.h> #include <string.h> // 引入strcspn函数所需的头文件 struct student { char name[100]; int roll; }; int main() { struct student st[2]; for (int i=0; i<2; i++) { char c; printf("\nEnter the details of student %d: \n", i+1); printf("Enter the name of the student: "); // 用fgets读取姓名,支持多单词,限制读取长度避免溢出 fgets(st[i].name, sizeof(st[i].name), stdin); // 把fgets读取到的换行符替换为字符串结束符 st[i].name[strcspn(st[i].name, "\n")] = '\0'; printf("Enter the roll number of the student: "); scanf("%d", &st[i].roll); // 清空缓冲区里的剩余字符(主要是换行符) while ((c = getchar()) != '\n' && c != EOF); } for (int i=0; i<2; i++) { printf("\nThe details of student %d: \n", i+1); printf("Name: %s\n", st[i].name); printf("Roll no.: %d\n", st[i].roll); } return 0; }
关键修改说明
strcspn(st[i].name, "\n")会返回换行符在姓名数组中的位置,直接替换为'\0'就能去掉多余的换行;while ((c = getchar()) != '\n' && c != EOF);循环会把缓冲区里从当前位置到换行符的所有字符都读走,确保下一次fgets能正确读取用户输入的姓名;- 全程用
fgets替代gets,彻底避免缓冲区溢出的安全隐患。
内容的提问来源于stack exchange,提问作者Rounak Singh
相关产品推荐
相关产品推荐

