You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:24:04