Reading a textfile line by line

How would I read each line from a *.txt and compare it to a user input string?

I can take a *.txt and compare the contents to a string so long as the file contains only one line but I have no idea how to do this with multiple lines.

I am trying to have the program accept user input and see if the *.txt file contains a matching word.
Use std::getline (the one that works with std::string):
http://www.cplusplus.com/reference/string/string/getline/
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(int argc, char *argv[])
{
    string word="";
    std::ifstream in("Test.txt");
    std::string contents((std::istreambuf_iterator<char>(in)), 
    std::istreambuf_iterator<char>());
    cin>> word;
    if(word == contents) {
                cout<< "\nRecognized.\n";
                getch(); }
    if(word != contents) {
         cout<< "\nNot recognized.\n"; 
         getch(); }
}


How would I use it in this scenario?
Assuming the *.txt file contained multiple words.
Does the text file contain more than one word per line?
Not at the moment (otherwise the program executes incorrectly) but I would like it to contain as many words as possible.
Here's a quick mock-up:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream file ("input.txt");
    std::string a, b;

    //To get a line from the file:
    std::getline(file, a);

    //To get a line from user input
    std::getline(std::cin, b);

    //...
}
Topic archived. No new replies allowed.