I'm doing an assignment for school which is to simulate the grep command in C++. We are to take in a word to search, an input file to search through, and output file to output the results. The only text that should be in the output file is the contents of each line that had the search word in it, with a line number of where it was in the input file. We are supposed to use the functions of <fstream>.
I'm a beginner to c++ and am having trouble wrapping my head around this problem. I don't know how to output just the line which has the word nor how to input a way of tracking line numbers.
What I have so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string keyword, inputFile, outputFile, line;
unsigned keywordCount = 0;
cout << "Enter word to search for: " << endl;
cin >> keyword;
cout << "Enter file to search through: " << endl;
cin >> inputFile;
cout << "Enter file to output results to: " << endl;
cin >> outputFile;
ifstream in( inputFile.c_str() );
if( !in ) {
cout << "Could not open: " << inputFile << endl;
return EXIT_FAILURE;
}
ofstream out;
out.open( outputFile.c_str() );
if( !out ) {
cout << "Could not open: " << outputFile << endl;
return EXIT_FAILURE;
}
while( getline( in,line ) ) {
if( line.find( keyword ) ){
out << line;
++keywordCount;
}
}
cout << keywordCount;
}
Any help is appreciated.