NoobLearner
NoobLearner

Reputation: 61

Compare string with data on a file

How can I take input from a user and compare it with data on a file?

Myfile.txt contains the following Data

Louise Ravel
Raven
Wings
Crosses and Bridges
Bjarne

In my Program

   #include <iostream>
   #include <fstream>
   #include <string>

   int main()
   {
       std::ifstream file("Myfile.txt");
       std::string name;
       std::cout<<"Enter the name to compare with the data: ";
       std::getline(std::cin,name);
       return 0;
   }

Now once the user enters the input, I want to compare the string entered with the data available in MyFile.txt and if a matching string is found then just simply print "Match Found"

I tried this one but it didn't work.

while(file>>name)
    {
        if(file==name)
        {
            cout<<"Match Found";
        }
    }

How can I do that?

Upvotes: 0

Views: 488

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36614

Your while loop is incorrect. You are reading your names from the file into the same variable as you read the user input from. You are also then comparing the file to the read name which will always return false.

Try:

std::string nameFromFile;
while(file>>nameFromFile)
{
    if(nameFromFile==name)
    {
        cout<<"Match Found";
    }
}

Upvotes: 1

Related Questions