0

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?

7
  • What have you tried? What didn't work? Stack overflow isn't a homework writing service. Commented Oct 22, 2018 at 9:45
  • I don't have any idea how to proceed about it? I've tried using while(file>>name) { if(file==name) { cout<<"Match Found"; } } but it didn't work Commented Oct 22, 2018 at 9:48
  • Edit your question to include that code. Did you try debugging? Commented Oct 22, 2018 at 9:49
  • I'm pretty much a beginner at programming so don't know anything about debugging Commented Oct 22, 2018 at 10:04
  • 1
    Learning to debug is far more important than learning to code, see ericlippert.com/2014/03/05/how-to-debug-small-programs Commented Oct 22, 2018 at 10:09

1 Answer 1

1

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";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.