检查数组的单词是否存在于C中的txt文件中

标签 c arrays string file pointers

我有一个单词数组:

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/

相关文章:

javascript - 使用 array.reduce 方法将二进制数字数组转换为十进制

java - 比较多个项目 bij 将这些元素添加到 2 arrayList 中

c++ - 在 C++ 中使用 getline 忽略空格

c - 如何阻止命令提示符出现在 Win32 C 应用程序中?

c - 释放 malloc 内存失败

c - .bss 部分的意义

ios - 修改结构时无法在不可变值错误上使用变异成员

c - 如何在linux中链接编译.c和.so文件

c++ - 如何在 C++ 中将字符串转换为 char*?

c++ - 静态初始化顺序和字符串连接