How to search for a word in a text file and if found print out the entire line

Darius  picture Darius · Apr 2, 2014 · Viewed 43.4k times · Source

My program needs to search for a word in a text file, and if it finds that word, to print out/display the entire line. Example:

employee   name    date joined    position       project        annual salary
tom jones           1/13/2011     accountant    pricing         55000
Susan lee           2/5/2007      Manager       policy          70000

User enters a search word:

accountant

Program searches text for accountant. When it finds it, it returns the following:

employee   name    date joined    position       project        annual salary
tom jones           1/13/2011     accountant    pricing         55000

This is the code I came up with but it doesn't work.

void KeyWord(ifstream &FileSearch)
{
     string letters;
     int position =-1;
     string line;
     ifstream readSearch;
     cout<<"enter search word ";
     cin>>letters;
     "\n";
     FileSearch.open("employee");
     if(FileSearch.is_open())
     { 
         while(getline(FileSearch, line))
         {
             FileSearch>>line;
             cout<<line<<endl;
             position=line.find(letters,position+1);
             if(position==string::npos);
             if(FileSearch.eof())
                 break;

             cout<<line<<endl;
         }

     }
     cout<<"Cant find"<<letters<<endl;
 }

Answer

Kevin picture Kevin · Apr 2, 2014

Easy answer:

void Keyword(ifstream & stream, string token) {
    string line;
    while (getline(stream, line)) {
        if (line.find(token) != string::npos) {
            cout << line << endl;
        }
    }
    cout << token << " not found" << endl;
}

In general, avoid mixing << and getline together when reading from a stream as it causes strange issues with line endings.