Scanning a *.txt file line by line and checking compatability

Jan 31, 2013 at 12:36am
How would I scan a *.txt file line by line to see if any of the lines in the *.txt file matched a string input by the user?
I am hoping that the program, when finished, will take a line input by the user and check a textfile to see if any words in the line match words in the textfile.
I have no idea how this could be done so any help at all is welcome.
Would some kind of For loop work for that?
Jan 31, 2013 at 1:18am
the line by line loop is usually written as

1
2
3
4
5
6
ifstream file("filename");
string line;
while(getline(file, line))
{
    // do things to line
}


although a for loop works too, and is even better in a way:

1
2
3
4
5
ifstream file("filename");
for(string line; getline(file, line); )
{
    // do things to line
}
Feb 1, 2013 at 12:50am
How would I use that to take each line from the file and compare them individually to a user input string and break the loop as soon as the words matched?
Last edited on Feb 1, 2013 at 12:51am
Feb 1, 2013 at 3:00am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <fstream>
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <string>

int main(int argc, char *argv[])
{
  if (argc != 3) {
    std::cout << "arg1 = inputfile, arg2 = words to find file\n";
    return 0;
  }
  std::ifstream words(argv[1]);
  std::ifstream toFind(argv[2]);

  if (!words.is_open() || !toFind.is_open()) {
    std::cout << "Could not open files\n";
    return 0;
  }

  std::vector<std::string> input;
  std::vector<std::string> search;
  
  std::istream_iterator<std::string> w_iter(words);
  std::istream_iterator<std::string> f_iter(toFind);
  std::istream_iterator<std::string> end;
  
  while (w_iter != end) input.push_back(*w_iter++);
  while (f_iter != end) search.push_back(*f_iter++);

  std::sort(input.begin(), input.end());  // Not needed?
  std::unique(input.begin(), input.end());  

  std::for_each(search.begin(), search.end(),
    [=](std::string& s) {
      if (std::find(input.begin(), input.end(), s) != input.end())
        std::cout << "Found: " << s << '\n';
    }
  );

  return 0;
}


Sorry if that doesn't work :P
Last edited on Feb 1, 2013 at 5:07am
Topic archived. No new replies allowed.