need to make a string matching program that takes input from a text file and out
ID: 3550369 • Letter: N
Question
need to make a string matching program that takes input from a text file and outputs that match (if there is one) asked from the user. i have done this part , the only problem is that , with the output match , i also need to print some words before and after the actual match , like you would search in google and it gives you the results , with extra details .... how could i do that sort of searching?
here is my program ..
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream myfile ("text.txt");
string line;
int offset;
string tosearch;
cout<< "Enter the word to be searched from the text file" << endl;
cin>> tosearch;
while (!myfile.eof())
{
getline(myfile,line);
if (offset = line.find(tosearch, 0) != string::npos)
{
cout << "The word has been found"<< endl;
}
}
cin.get();
return 0;
}
Explanation / Answer
change the following code:
while (!myfile.eof())
{
getline(myfile,line);
if (offset = line.find(tosearch, 0) != string::npos)
{
cout << "The word has been found"<< endl;
}
}
to this:
while (!myfile.eof())
{
getline(myfile,line);
if (offset = line.find(tosearch, 0) != string::npos)
{
cout << "The word has been found in the following line:"<< endl;
cout<<line<<endl;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.