Write a C program that allows the user to search a file MyTe
Write a C++ program that allows the user to search a file “MyText.txt” located in the current workspace for any word (String). The program should print the result of the search. In the event the word is found the program should indicate the line where it was found in the text file.
Example:
Enter the word you are looking for: John
The word John was not found!
Or
Enter the word you are looking for: John
The word John was found in line 3 of the text file!
Solution
#include <iostream>
 #include <fstream>
 using namespace std;
int main()
 {
 string key;// string to store the input from the user
 cout<<\"Enter the word you are looking for: \";
 cin>>key;
 int line=0;// count variable to count the line number
 bool isFound=false;
 ifstream in(\"MyText.txt\");// reading the MyText.txt file
 if(!in) {// condition when the file cannot be opened
 cout << \"the file cannot be opened.\ \";
 return 1;
 }
 string str;// variable to store each line
 while (getline(in, str)) {
 // output the line
 line++;// incrementing counter of line by 1
 //condition to check if the string str contains our key
 if (str.find(key) != std::string::npos) {
 isFound=true;
 break;// breaking from the loop once found
 }
// now we loop back and get the next line in \'str\'
 }
 // if line!=0 the word/key was found
 if(line && isFound) {
 cout<<\"The word \"<<key<<\" was found in line \"<<line<<\" of the text file!\";
 } else { //else not found
 cout<<\"The word \"<<key<<\" was not found!\";
 }
 in.close();
 return 0;
 }
 ----------------dummy MyText.txt file----------------
 Hello World
 Again its a same day
 John was here
 ok quitting now
----------------------------------------------------------
 save the above file as MyText.txt in the current workspace
 --------------------output-----------------
 Enter the word you are looking for: John
 The word John was found in line 3 of the text file!
Enter the word you are looking for: Earth   
 The word Earth was not found!
----------------output ends-----------------


