我想在.txt文件中搜索特定字词。
例如该文件包含“Jon Miller,Andy Miller,Apu McDawn” 我想在这个文件中搜索“米勒”的频率。 然后它应该显示数字(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;
}
答案 0 :(得分:0)
您尚未为string
分配任何内存。变化
char *string;
要
char string[100];
或动态分配内存
string=malloc(100);
使用
使用后将其释放free(string);
同时更改
while(!feof(in_file))
要
while(fscanf(in_file,"%s", string))
删除此循环体内的fscanf
。阅读this以了解我为何进行了此项更改。并在您的计划中加入string.h
。
答案 1 :(得分:-2)
我的朋友我刚刚将strcmp函数更改为strncmp。 &安培;有用。 这两个函数都比较两个字符串。 strcmp()将整个字符串向下比较,而strncmp()只将strings.nction strcmp的前n个字符与strncmp进行比较。
他们回归的时候有点时髦。基本上它是字符串的差异,所以如果字符串相同,它将返回零(因为差异为零)。如果字符串不同,它将返回非零;基本上它会找到第一个不匹配的字符,如果字符串中的字符小于字中的相应字符,则返回小于零。如果字符串中的字符大于字中的字符,则返回大于零。
#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("ser.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(!strncmp(string , word))//if hit a word
num++;
}
printf( "%d Hit \n" ,num );
}
return 0;
}