In: Computer Science
You will develop a program in C++ that will do a "find and replace" on an input file and write out the updated file with a new name.
It will prompt your user for four inputs:
The name of the input file.
The characters to find in the input file.
The replacement (substitute) characters.
The name of the output file.
It will perform the replacement.
Note1: all instances must be replaced not just the first one on a line.
Note2: this is a case sensitive replacment
Sample Output:
Welcome to the find and replace utility!
Input filename? AllOfMe.txt
Find what? Love
Replace with? Hate
Output filename? AOM_out
Input File:
Cause all of me
Loves all of you
Love your curves and all your edges
All your perfect imperfections
Output File
Cause all of me
Hates all of you
Hate your curves and all your edges
All your perfect imperfections
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char inputFile[100];
char outputFile[100];
string inpFileText;
string outFileText;
// reading filename
cout << "Enter Input filename ? ";
cin >> inputFile;
ifstream file1(inputFile);
// checking file exists or not
if(file1.fail()){
cout << "File not exist" <<endl;
exit(0);
}
// read all text from file
string text;
string fulltext="";
while (getline (file1, text)) {
fulltext = fulltext + text + "\n";
}
// inpFileText contains text of file of inputFile
inpFileText = fulltext;
string find, replace;
// reading find and replace strings
cout << "Find What ? ";
cin >> find;
cout << "Replace with ? ";
cin >> replace;
cout << "Output filename ? ";
cin >> outputFile;
int index;
// replacing find string with replace string
while((index = fulltext.find(find)) != string::npos) {
fulltext.replace(index, replace.length(), replace);
}
// storing replaced string to outFileText
outFileText = fulltext;
cout <<endl;
// writing outFileText string to outputFile
ofstream file2(outputFile);
file2 << outFileText;
// printing input file text
cout << "------------Input File Text-----------" <<endl;
cout << inpFileText <<endl;
// printing output file text
cout << "-----------Output File Text-----------" <<endl;
cout << outFileText <<endl;
return 1;
}
Output: