在两个文本文件中搜索单词

Search words in two text files c++

本文关键字:文件 搜索 单词 文本 两个      更新时间:2023-10-16

我是新来的。无论如何。我试图搜索一个词在一个文本文件(其中有10个句子)从一个文本文件,由几个关键字。基本上,我试图找到如果一个关键字在file2包含在file1。我试过了,但它似乎是按行而不是按词比较的。有谁能帮我一下吗?谢谢。

int main()
{
  bool Found;
  int i = 0;
  int j = 0;
  string str;
  ifstream file;
  file.open("words.txt", ios::in | ios::binary);
  string str2;
  ifstream file2;
  file2.open("M4.txt", ios::in | ios::binary);
  while (!file.eof() && !Found) {
    getline(file, str, ' ');
  }
  while (!file2.eof() && !Found) {
    getline(file2, str2, ' ');
  }
  //  if (str == str2)
  if (file.get() == file2.get()) {
    cout << "This order is valid. M3" << endl;
  } else {
    cout << "This order is invalid. M3" << endl;
  }
  system("pause");
  return 0;
}
我希望任何人都能帮上忙。已经在这里呆了几个星期了

这里有两个问题:如何将文件分割成令牌,以及如何搜索集合中的元素,标准库为这两个问题提供了解决方案。

#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
  using It = std::istream_iterator<std::string>;
  std::ifstream text_file("words.txt");
  std::ifstream words_file("M4.txt");
  std::vector<std::string> text{It(text_file), It()};
  std::vector<std::string> words{It(words_file), It()};
  bool result = std::find_first_of(
    text.begin(), text.end(), 
    words.begin(), words.end()
  ) != text.end();
  std::cout << result << 'n';
}

如果您需要知道哪些单词匹配,您可以使用std::set s或sort作为向量,然后使用std::set_intersection创建一个新的范围

std::vector<std::string> result;
std::sort(text.begin(), text.end());
std::sort(words.begin(), words.end());
std::set_intersection(
  text.begin(), text.end(),
  words.begin(), words.end(),
  std::back_inserter(result)
);
for (auto& s : result)
  std::cout << s << 'n';