C语言代码无法读取地址输入,对应的bug该如何排查修复?
问题根因
跳过输入问题的根因为输入缓冲区残留换行符:
- 调用
scanf("%ld", &s.a)读取账号数字时,输入完成后按下的回车对应的\n换行符不会被scanf处理,会残留在输入缓冲区中 - 后续调用
gets(s.add)时,会优先读取缓冲区里的残留换行符,直接判定为输入结束,因此看起来跳过了地址输入环节
另外gets函数本身无输入边界校验,存在严重缓冲区溢出风险,已被C标准正式废弃,建议统一使用fgets处理字符串输入。
修复方案
在scanf读取数字的代码后增加清空输入缓冲区的逻辑即可,修复后代码如下:
#include <stdio.h> #include <string.h> struct acho { char ahn[50], add[200]; long int a, bal; }; // 清空输入缓冲区辅助函数 void clear_buffer() { int c; while ((c = getchar()) != '\n' && c != EOF); } int main() { struct acho s; printf("enter name: \n"); fgets(s.ahn, sizeof(s.ahn), stdin); // 移除fgets读取到的末尾换行符 s.ahn[strcspn(s.ahn, "\n")] = '\0'; printf("enter number: \n"); scanf("%ld", &s.a); clear_buffer(); // 读取数字后清空残留的换行符 printf("enter address: \n"); fgets(s.add, sizeof(s.add), stdin); s.add[strcspn(s.add, "\n")] = '\0'; printf("enter balance: \n"); scanf("%ld", &s.bal); printf("Name: %s \n", s.ahn); printf("Account number: %ld \n", s.a); printf("Address: %s \n", s.add); printf("Balance: %ld \n", s.bal); return 0; }
修复说明
- 新增
clear_buffer函数,遍历读取缓冲区内容直到遇到换行符或文件结束符,彻底清空残留内容 - 替换所有
gets为更安全的fgets,同时通过strcspn移除fgets默认读取的末尾换行符,避免输出时出现多余空行 - 所有
scanf读取非字符串类型内容后,都需要调用一次清空缓冲区逻辑,避免后续字符串输入被干扰
内容的提问来源于stack exchange,提问作者Akash Gautam
相关产品推荐
相关产品推荐

