我想在 .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/