Answer to Question #230453 in Functional Programming for Usman

Question #230453

Task 2:

Write C++ program, with multiple functions, that reads text, txt, from the file and accepts two patterns, pat and rpat, from the user. The program replace all occurrences of pat from the txt with rpat. The program output shall be as shown below in the example.


1
Expert's answer
2021-08-30T14:42:48-0400
#include <iostream>
#include <string>
#include <fstream>


using namespace std;
//this function allows to replace string
void replace(string& line, string pat, string rpat){
	size_t position = line.find(pat);
	while(position != string::npos){
		line.replace(position, pat.size(), rpat);
		position =line.find(pat, position + rpat.size());
	}
}


void readFromFile(string fileNameFrom,string fileNameTo, string pat, string rpat){
	string line;
	ifstream file(fileNameFrom);
	ofstream fileSave;
	fileSave.open (fileNameTo);
	while (getline (file, line)) {
		replace(line,pat,rpat);
		fileSave <<line<< "\n";
	}
	// Close the file
	file.close();
	fileSave.close();
}


int main(){
	string fileNameFrom="input1.txt";
	string fileNameTo="input2.txt";
	 string pat;
	 string rpat;

	cout<<"Enter the file name to read: ";
	getline(cin,fileNameFrom);
	cout<<"Enter the file name to save: ";
	getline(cin,fileNameTo);

	cout<<"Enter pat: ";
	getline(cin,pat);
	cout<<"Enter rpat: ";
	getline(cin,rpat);


	readFromFile(fileNameFrom,fileNameTo,pat, rpat);

	system("pause");
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS