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

为何使用scanf与fgets获取子串时,C语言搜索程序结果不同?

为什么用fgets获取子串时C程序结果异常?

先看你提供的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char track[][80] = {"I left my heart in Havard Med School",
"Newark, Newark - a wonderful town",
"Dancing with a Dork",
"From here to maternity",
"The girl from Iwo Jima",
};

void find_song(char *search)
{
    for(int i = 0; i < 5; i++){
        if(strstr(track[i], search))
            printf("Track %i: %s\n\n", i, track[i]);        
    }
}

int main(){
    char search[80];
    printf("search track: ");
    //fgets(search, 80, stdin);  initial line the book used
    scanf("%79s", search); // my line
    find_song(search);
}

问题核心在于fgets和scanf的读取行为差异:

  • scanf("%79s", search)会自动跳过输入开头的空白字符,读到空格、换行这类空白字符就停止读取,不会把换行符存入search数组,还会自动在末尾添加\0作为字符串结束标记。
  • 而fgets(search, 80, stdin)会把你输入内容时按下的**换行符\n**也一起读到search里,比如你输入Dork再回车,search里实际存储的是"Dork\n\0"。

之后调用strstr匹配时,它会在track的字符串里寻找包含"Dork\n"的子串,但track里的所有字符串都不带换行符,自然匹配不到,就会出现结果异常的情况。

解决方法很直接,用strcspn去掉fgets读入的换行符即可:

fgets(search, 80, stdin);
// 把换行符替换为字符串结束符
search[strcspn(search, "\n")] = '\0';

处理后search的内容就和scanf读入的一致,strstr就能正常完成匹配了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:35:04