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

fgets()提前触发问题求助:程序启动即要求5次输入

C语言输入异常问题分析与解决

你的代码如下:

int main (void){
    
    Article article;
    char title[100], author[100], journal[100], newtitle[100];
    int year;
    
    fgets(title, 80, stdin);
    fgets(author, 80, stdin);
    fgets(journal, 80, stdin);
    scanf("%d", &year);
    
    article = create_article(title, author, journal, year);
    print_format_full(article);
    
    fgets(newtitle, 80, stdin);
    article = update_title(article, newtitle);
    
    print_format_simplified(article);
    // insert your code here
    
    return 0;

}

错误原因

问题出在scanf("%d", &year);的使用上:

  • 当你输入年份并按下回车时,scanf只会读取数字部分,回车产生的换行符会残留在标准输入缓冲区中。
  • 后续调用fgets(newtitle, 80, stdin);时,fgets会直接读取缓冲区里的换行符,不会等待你输入新标题。这就导致你误以为程序要求输入5次内容——实际上第4次输入年份后的回车被当成了新标题的输入,程序后续流程跳过了你的手动输入。

解决方法

方法1:清空scanf残留的换行符

在scanf执行后,手动读取并丢弃缓冲区里的换行符:

scanf("%d", &year);
// 清空缓冲区直到遇到换行符,避免残留空白字符
while(getchar() != '\n');

这种方式能处理用户输入年份后附带多个空白字符(如空格+回车)的情况,确保缓冲区被彻底清空。

方法2:统一使用fgets读取所有输入

避免scanf和fgets混用,用fgets读取年份的字符串,再转换成整数:

char year_str[20];
// 读取年份字符串
fgets(year_str, sizeof(year_str), stdin);
// 转换为整数
year = atoi(year_str);

这种方式不会留下残留的换行符,输入逻辑更统一,减少缓冲区异常的概率。

内容的提问来源于stack exchange,提问作者chupi 8904

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:10:48