Reputation: 35
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.
Upvotes: 0
Views: 806
Reputation: 473
The issue is that you are reading word by word. A stream uses "\n" as a token seperater. Hence it is ignored during word reading. Use getline standard function to get a line.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main(){
string inputFileName = "inputFile.txt";
string outputFileName = "outputFile.txt";
fstream inputfile;
ofstream outputFile;
inputfile.open(inputFileName.c_str());
outputFile.open(outputFileName.c_str());
string keyWord = "morning";
string line;
while (std::getline(file, line)) {
// Processing from the beginning of each line.
if(line.find(keyWord) != string::npos)
outputFile << line << "\n";
}
}
Got the idea from the answer in Read file line by line using ifstream in C++
Upvotes: 1