In this function I need to replace all chars in a file that is inputted, e.g. an a, with another char inputted, e.g. an i. I have given it two shots but as I am new and it’s way too late for my brain to even work any advice?
void swapping_letter()
{
ifstream inFile("decrypted.txt");
char a;
char b;
string line;
if (inFile.is_open())
{
while (!inFile.eof())
{
getline(inFile,line);
}
cout<<"What is the letter you want to replace?"<<endl;
cin>>a;
cout<<"What is the letter you want to replace it with?"<<endl;
cin>>b;
replace(line.begin(),line.end(),a,b);
inFile<<line
inFile.close();
}
else
{
cout<<"Please run the decrypt."<<endl;
}
}
or:
void swapping_letter()
{
ifstream inFile("decrypted.txt");
char a;
char b;
if (inFile.is_open())
{
const char EOL = '\n';
const char SPACE = ' ';
cout<<"What is the letter you want to replace?"<<endl;
cin>>a;
cout<<"What is the letter you want to replace it with?"<<endl;
cin>>b;
vector<char> fileChars;
while (inFile.good())
{
char c;
inFile.get(c);
if (c != EOL && c != SPACE)
{
fileChars.push_back(c);
}
replace(fileChars.begin(),fileChars.end(),a,b);
for(int i = 0; i < fileChars.size(); i++)
{
inFile<<fileChars[i];
}
}
}
else
{
cout<<"Please run the decrypt."<<endl;
}
}
One way of doing this is to read the original file, replace characters and write the output to a new file.
Then eventually when you are done probably overwrite the old file with the new.