【问题标题】:Search for words in a txt file在 txt 文件中搜索单词
【发布时间】:2022-01-06 16:07:06
【问题描述】:

我试图编写一个程序来搜索文件中的单词,这是我写的,但它不起作用。 我希望该程序读取在空格中缩放的文本部分。 当我运行它并写下“Hello”时,我什么都不做并结束,但我想要它,以便输出是:

Hello
coolcool
horse
miein

Hello
cookiecookie
horse
lol

代码如下:

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

#define max 30

int main() {
    FILE *file;
    char c[max + 1];
    int x;
    char input[max + 1];
    char suche[max + 1];
    char output[max + 1];

    printf("Please write the word to search ");
    fgets(input, max, stdin);

    file = fopen("Testo.dat", "r");

    //here does the programm fail
    while (feof(file) != 0) {
        fgets(suche, max, file);
        if (strcmp(input, suche) == 0) {
            for (x = 0; x < 4; x++) {
                fgets(output, max, file);
                printf("%s", output);
            }
        }
    }

    fclose(file);
    return 0;
}

这是要搜索文本部分的文件:

Hello
coolcool
horse
miein

Hello
cookiecookie
horse
lol

This
testetst
door
nicht

Thoes
breadbread
read
ja

【问题讨论】:

  • 您是在调试器中调试程序还是在其中放入了一些 printf 语句?
  • Why is “while ( !feof (file) )” always wrong? - 在你的代码中这是特别错误的,因为你有嵌套循环 fgets 根本没有检查 EOF
  • 次要:fgets(input, max, stdin); 的大小比它可以使用的小 1。使用fgets(input, max +1, stdin); 甚至更好:fgets(input, sizeof input, stdin);

标签: c file


【解决方案1】:

为了简化调试,您应该正确测试这些条件:

  • fgets(input, max, stdin) 是否成功读取用户的字符串?
  • fopen("Testo.dat", "r") 是否成功打开字典文件?
  • fgets(suche, max, file) 是否成功地从字典中读取了一个字符串?事实上,读取循环在尝试读取之前不应该测试feof(file),它应该只测试fgets() 是否成功。

有意义的错误消息将有助于确定程序失败的地方。

还请注意,您应该将目标数组的大小传递给fgets()max + 1,而不是max。由于input 是一个数组,所以只需传递sizeof input

这是修改后的版本:

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

#define BUFFER_SIZE  32

int main() {
    char input[BUFFER_SIZE];
    char suche[BUFFER_SIZE];
    char output[BUFFER_SIZE];
    FILE *file;

    printf("Please write the word to search: ");
    if (!fgets(input, sizeof input, stdin)) {
        printf("input error\n");
        return 1;
    }
    file = fopen("Testo.dat", "r");
    if (file == NULL) {
        perror("Cannot open Testo.dat");
        return 1;
    }
    while (fgets(suche, sizeof suche, file)) {
        if (strcmp(input, suche) == 0) {
            for (int x = 0; x < 4; x++) {
                if (fgets(output, sizeof output, file))
                    printf("%s", output);
            }
        }
    }
    fclose(file);
    return 0;
}

另请注意,fgets() 读取整行,包括尾随换行符,因此只有当字典包含不带空格的单词时,您才能找到匹配项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多