user3659038
user3659038

Reputation: 35

Search words in two text files c++

I am new here. Anyway. I am trying to search a word in a text file(which has 10 sentences) from a text file that consists of few keywords. Basically i am trying to find if one of the keywords in file2 consist in file1. I have tried but it seems like it compares by line instead of word. if anyone could help me with this? thanks.

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;
}

I hope anyone can help with this. Have stuck at here for weeks :(

Upvotes: 0

Views: 1262

Answers (1)

user657267
user657267

Reputation: 21000

There are two problems here: how to split a file into tokens, and how to search for an element of a set, the standard library provides solutions for both.

#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';
}

If you need to know which words match, you can either use std::sets, or sort the vectors, and then use std::set_intersection to create a new range

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';

Upvotes: 1

Related Questions