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.
#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;
}
Comments
Leave a comment