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

C语言中STDIN输入子串匹配文件内容失败的问题排查

问题分析与解决:字符串文件查找失效问题

问题描述

我需要完成以下简单任务:

  • 用户输入一个字符串,用于在文本文件中查找是否存在;
  • 若找到该字符串,打印文本文件中所有包含该字符串的行;
  • 程序终止/函数结束。

目前已实现文件读取功能,但结合用户输入时出现问题:例如用户输入sushi时,无法打印文件中包含sushi的行,但手动将参数传入strstr(如strstr(lineOfText,"sushi"))时可正常运行。

现有代码

#include <stdio.h>
#include <string.h>

#define MAX_LINE_LENGTH 250  // 补充缺失的宏定义

int main() {
    word_search();
    return 0;
}

int word_search() {
    FILE *textFile;
    char line[MAX_LINE_LENGTH];

    textFile = fopen("PATH TO TEXT FILE", "r");

    if (textFile == NULL) {
        return 1;
    }
    printf("Please input word to search:");
    char userInput[] = "";
    fgets(userInput, 250, stdin);

    while (fgets(line, MAX_LINE_LENGTH, textFile)) {
        if (strstr(line, userInput) != NULL) {
            printf("%s", line);
        }
    }

    fclose(textFile);
    return 0;
}

文件内容

1 Wallaby Way Fenwick
1 Sushi Way Fenwick
1 Wallaby Sushi Way Fenwick
1 Alexandria Way Fenwick
1 Alexandira Sushi Ashfield Way Fenwick

问题原因

  1. 缓冲区溢出问题:char userInput[] = ""; 初始化的数组仅能容纳1个字符(字符串终止符\0),调用fgets(userInput, 250, stdin)时,输入的内容会超出数组容量,导致内存越界,触发未定义行为。
  2. 换行符干扰匹配:fgets会将用户输入结束时按下的换行符\n一并读取到userInput中,而文件内的行内容并不包含这个换行符,因此strstr无法匹配到目标字符串。

修正方案

  1. 为userInput分配足够的存储空间,比如定义为char userInput[250];
  2. 移除userInput末尾的换行符,确保匹配的字符串和文件中的内容一致。

修正后的代码

#include <stdio.h>
#include <string.h>

#define MAX_LINE_LENGTH 250

int main() {
    word_search();
    return 0;
}

int word_search() {
    FILE *textFile;
    char line[MAX_LINE_LENGTH];
    char userInput[250];  // 分配足够空间

    textFile = fopen("PATH TO TEXT FILE", "r");

    if (textFile == NULL) {
        return 1;
    }
    printf("Please input word to search:");
    fgets(userInput, sizeof(userInput), stdin);

    // 移除换行符
    userInput[strcspn(userInput, "\n")] = '\0';

    while (fgets(line, MAX_LINE_LENGTH, textFile)) {
        if (strstr(line, userInput) != NULL) {
            printf("%s", line);
        }
    }

    fclose(textFile);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:45:57