I've written a program that asks the user what letter to replace, and what to replace it with.
It runs, and works as it should the first time, however it will only ever save one round of swapping. i.e. when I run it again the letter I originally swapped just reverts back to the original.
I have no idea why it does this, and was wondering if anyone could see what I've done wrong.
#include <iostream>
#include <fstream>
#include <algorithm>
#include <ctype.h>
#include <cstdio>
usingnamespace std;
int main()
{
char RunAgain = 'y';
do// do while loop to re-run the program
{
ifstream inputFile("swapped.txt");
ofstream outputFile("final_decrypted.txt");
char x;
char y;
char letter;
cout << "Enter the character that you want to replace" << endl;
cin >> x;
cout << "Enter the character that you want to replace it with" << endl;
cin >> y;
if (inputFile.is_open())
{
while (inputFile.good())
{
inputFile.get(letter);
if (letter == x)
{
outputFile << y;
}
else
{
outputFile << letter;
}
}
cout << "Enter y to run this program again. Enter any other letter to quit. ";
cin >> RunAgain;
}
}
while (RunAgain == 'y');
return 0;
}
Alternatively, if anyone knows a simpler way to replace one letter with another in a text file that would be awesome. Any help would be appreciated. Cheers.
Each time your do-while loop iterates, you re-read the contents of swapped.txt. Since you don't update swapped.txt with the results of the swapping (you write them instead to final_decrypted.txt), it will always have the same contents at at did at the start of the first run.
#include <iostream>
#include <fstream>
#include <cstdio>
int main()
{
constchar* const file_name = "swapped.txt" ;
constchar* const temp_file_name = "final_decrypted.txt" ;
char RunAgain = 'y';
while( (RunAgain=='y') || (RunAgain=='Y') )
{
char x ;
std::cout << "Enter the character that you want to replace: " ;
std::cin >> x;
char y ;
std::cout << "Enter the character that you want to replace it with: " ;
std::cin >> y;
{
std::ifstream ifile(file_name) ; // open input file for reading
std::ofstream ofile(temp_file_name) ; // open temp file for writing
char c ;
while( ifile.get(c) ) // for every character (including white space) in ifile
ofile.put( c == x ? y : c ) ; // write (replaced) character to ofile
}
// copy contents of temp file to the original file
{ std::ofstream(file_name) << std::ifstream(temp_file_name).rdbuf() ; }
std::remove(temp_file_name) ; // delete the temp file
std::cout << "Enter y to run this program again. Enter any other letter to quit: " ;
std::cin >> RunAgain;
}
// examine the contents of the modified file
std::cout << "\n\n\n" << std::ifstream(file_name).rdbuf() ;
}
rdbuf() returns (a pointer to) the stream buffer - in this case a std::filebuf.
When we use << with an output stream and a stream buffer, every character from the stream buffer is written to the output stream. (This is faster than our reading characters one by one, and then writing out each character that was read.)