Task: Create program to read given text file and print into another text file all lines containing given substring. Reading from files should be carried out line per line.
My code:
#include <bits/stdc++.h>
#include <iostream>
#include <fstream>
using namespace std;
int main(){
fstream file; // required for input file further processing
ofstream outputFile;
string word1, word2, t, q, inputFileName;
string keyWord = "morning";
string enterKey = "\n";
inputFileName = "inputFile.txt";
file.open(inputFileName.c_str()); // opening the EXISTING INPUT file
outputFile.open("outputFile.txt"); // CREATION of OUTPUT file
// extracting words from the INPUT file
while (file >> word1){
if(word1 == keyWord) {
while(file >> word2 && word2 != enterKey){
// printing the extracted words to the OUTPUT file
outputFile << word2 << " ";
}
}
}
outputFile.close();
return 0;
}
1st problem: outputFile contains the whole text, in other words while loop is not stopping at the place whre enter is pressed.
2nd problem: Processing of string is not starting from the beginning of the text.