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 replacement
And it should allow the string to find or the replacement to contain blanks.
It must have at least 2 functions in addition to main. Note: functions should be after main with their prototypes before main.
And it should be checking for output file failure
Sample Output:
Welcome to the find and replace utility!
Input filename? AllOfMe.txt
Find what? all
Replace with? most
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 most of me
Loves most of you
Love your curves and all your edges
All your perfect imperfections
#include <bits/stdc++.h>
#include <string>
using namespace std;
int getStringLength(string sourceString);
string replaceString(string sourceString,string findWhat, string replaceWith);
// Driver code
int main()
{
string inputFileName,findWhat,replaceWith,outputFileName,line;
cout<<"\n Welcome to the find and replace utility";
cout<<"\n Input File Name ?";
cin>>inputFileName;
cout<<"\nFind What?";
cin>>findWhat;
cout<<"\n Replace With?";
cin>>replaceWith;
cout<<"\n Output File Name?";
cin>>outputFileName;
ifstream myfile (inputFileName+".txt");
if (myfile.is_open())
{
ofstream MyFile(outputFileName+".txt");
while ( getline (myfile,line) )
{
string finalString = replaceString(line, findWhat,replaceWith);
MyFile<<finalString<<"\n";
}
myfile.close();
MyFile.close();
} else {
cout<<"Could not open the source file";
}
}
string replaceString(string sourceString,string findWhat, string replaceWith)
{
string str = sourceString;
size_t index = 0;
while (true) {
/* Locate the substring to replace. */
index = str.find(findWhat, index);
if (index == std::string::npos) break;
/* Make the replacement. */
str.replace(index, getStringLength(findWhat), replaceWith);
/* Advance index forward so the next iteration doesn't pick it up as well. */
index += getStringLength(findWhat);
}
return str;
}
int getStringLength(string sourceString) {
int length =0 ;
length = sourceString.length();
return length;
}