我有一个单词数组:
const char *words[3]={cat,dog,snake,bee};
还有一个像这样的txt文件:
apple tree day night story bee oil lemons get fight 234 meow woof safari
jazz stuff what is dog fight street snake garden glass house bee question
foot head 29191 43493 ==
(我们不知道这个文件有多少行)
我想检查整个文件,每次我找到数组中的一个单词时打印该单词并打印找到它的行。
我在比较时遇到了问题。我的想法是将文件的每个单词保存到一个数组中,并将每个单词与 words 数组中的单词进行比较。但我不能那样做。我有这个:
FILE *f;
const char *arr;
f=fopen("test.txt","r");
while(fscanf(f,"%s",arr)!EOF)
我真的不知道在这里写什么,所以我把文件分成了单词。
请善待我,我只是在努力学习。
最佳答案
您提供的代码片段中存在几个问题:
const char *words[3]={cat,dog,snake,bee};
这里你声明了一个包含 3 个元素的数组,但是你有 4 个初始化器。而且你忘了把单词放在引号之间。
这里你使用fscanf
读入arr
,但是你没有分配内存,arr
没有初始化,你可能是想写char arr[200]
,200是最大字长。
FILE *f;
const char *arr;
f=fopen("test.txt","r");
while(fscanf(f,"%s",arr)!EOF)
你想要这个作为基础,但仍有改进空间:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *words[] = { "cat", "dog", "snake", "bee" };
int main()
{
char line[200]; // maximum line size is 200
size_t len = 0;
FILE *f;
f = fopen("test.txt", "r");
if (f == NULL)
{
printf("Can't open file\n");
return 1;
}
int line_no = 0;
while (fgets(line, sizeof line, f))
{
++line_no;
// (sizeof words)/sizeof *words is the the number of words in the words array
for (int i = 0; i < (sizeof words)/sizeof *words; i++)
{
if (strstr(line, words[i]) != NULL)
{
printf("found %s in line %d\n", words[i], line_no);
}
}
}
fclose(f);
}
关于检查数组的单词是否存在于C中的txt文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42431763/