C语言代码运行时fgets被跳过、scanf运行正常的问题求解
问题原因
scanf("%i")仅会读取输入流中的整数内容,用户输入学号后按下回车产生的\n换行符会残留在标准输入缓冲区stdin中。fgets的读取逻辑是遇到换行符就终止读取,因此调用时会直接读取到这个残留的换行符,返回仅包含换行符的短字符串,肉眼看起来就像fgets被跳过、没有等待用户输入。
可行修复方案
- 方案1:单字符清理残留换行
适合确定缓冲区仅残留单个换行符的场景,直接调用一次getchar()吃掉换行即可:void get_information(){ printf("Type your student ID: "); scanf("%i", &student_t.studentID); getchar(); // 消化输入学号后残留的换行符 printf("\nType your name: "); fgets(student_t.studentName, 100, stdin); printf("\nType your age: "); scanf("%i", &student_t.age); } - 方案2:循环清空全部缓冲区残留
兼容用户输入学号时多输入了空格、特殊字符的场景,把缓冲区所有残留内容全部清理干净:void get_information(){ printf("Type your student ID: "); scanf("%i", &student_t.studentID); // 循环读取缓冲区直到遇到换行符或流结束 int c; while ((c = getchar()) != '\n' && c != EOF); printf("\nType your name: "); fgets(student_t.studentName, 100, stdin); printf("\nType your age: "); scanf("%i", &student_t.age); } - 方案3:统一输入函数避免混用冲突
全部使用fgets读取输入内容,再用sscanf解析数值,从根源上避免不同输入函数的缓冲区兼容问题:void get_information(){ char buffer[100]; printf("Type your student ID: "); fgets(buffer, sizeof(buffer), stdin); sscanf(buffer, "%i", &student_t.studentID); printf("\nType your name: "); fgets(student_t.studentName, 100, stdin); printf("\nType your age: "); fgets(buffer, sizeof(buffer), stdin); sscanf(buffer, "%i", &student_t.age); }
额外提示:fgets读取到的字符串默认会包含用户输入结束时的换行符,如果不需要保留姓名末尾的换行,可以在读取完成后添加代码
student_t.studentName[strcspn(student_t.studentName, "\n")] = '\0';手动清除。
内容的提问来源于stack exchange,提问作者user16003119
相关产品推荐
相关产品推荐

