7

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;
 }
anatolyg
  • 26,506
  • 9
  • 60
  • 134
Darius
  • 85
  • 2
  • 4
  • 12

1 Answers1

14

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.

Community
  • 1
  • 1
Kevin
  • 247
  • 1
  • 6
  • thanks I will try this right now..and repost the results, or quesitons.. I'm guessing where you have the word token..Im going to replace with letters.. where i get input from user..? – Darius Apr 02 '14 at 03:58
  • updated since I just noticed a bug. The if statement should have a != string::npos. And yeah just replace the string token with whatever you are looking for (accountant in your example) – Kevin Apr 02 '14 at 04:03
  • Perfect it work... Thank you so much..Kevin..I really appreciate it..YOur the best dude..Thanks again – Darius Apr 02 '14 at 04:16