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

My program should look for a word in a text file, and if it finds that word, print / 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 70,000

The user enters the search word:

accountant

The program searches for text for accountant . When he finds this, he 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 does not 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; } 
+8
c ++ string-matching io
source share
2 answers

Simple 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 stream as this causes strange problems with line endings.

+14
source share

I have a problem using this code when I call a function, it says that there is no instance of the overloaded function, I could solve it by passing my ifstream and the word that I need to find as an argument, but still gives error C2660, cant function accept two arguments. Help me please

0
source share

All Articles