c - 读取 .txt 文件中的单词不起作用 C

标签 c file numbers

我想在 .txt 文件中搜索特定单词。

例如,文件包含“Jon Miller、Andy Miller、Apu McDawn” 我想在这个文件中搜索“Miller”它出现的频率。 那么它应该显示数字(num)“2”

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

int main(int argc, char const *argv[])
{   
    int num =0;
    char word[100];
    char *string;

    FILE *in_file = fopen("test.txt", "r"); //reading the words

    if (in_file == NULL)
    {
        printf("Dataerror\n"); //if word not found
        exit(-1);
    }

    else {
        scanf("%s", word);
        printf("%s\n", word);

        while(!feof(in_file))//search for the word

        {
            fscanf(in_file,"%s", string);
            if(!strcmp(string , word))//if hit a word
            num++;
        }

        printf( "%d Hit \n" ,num );
    }
    return 0;
}

最佳答案

您尚未为字符串分配任何内存。改变

char *string;

char string[100];

或者动态分配内存

string=malloc(100);

并在使用后释放它

free(string);

也改变

while(!feof(in_file))

while(fscanf(in_file,"%s", string))

并删除该循环体内的fscanf。阅读 this知道我为什么要做出这样的改变。并在您的程序中包含 string.h

关于c - 读取 .txt 文件中的单词不起作用 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28151590/

相关文章:

file - 在 Go 中使用相同的 *os.File 写入和读取文件

iPhone/iPad IOS 文件权限/沙箱无论如何都要向另一个应用程序授予权限?

c - 使用定义变量的 srand() 生成随机数

c - 这个指令是什么意思(subl $20,%esp)?

c - 宏函数的不需要的(或不稳定的)结果

c 程序将媒体文件从一个位置复制到另一个位置

javascript - 在文本区域中显示行号

c - 数字生成器未在 C 中打印出预期的第一个数字

c - 纹理映射位置不精确

python - 是什么导致 C 程序不能在 Arduino 中正确地递增变量?