I have code that works but only once. I need an input char a to be swapped with an input char b. The first time through the loop, it swaps the two selected chars fine, but on the second and following iterations it does nothing but keep the outFile the same. How can I swap more than two chars until I want to stop?
ifstream inFile("decrypted.txt");
ofstream outFile("swapped.txt");
const char exist = 'n';
char n = '\0';
char a = 0;
char b = 0;
cout<<"\nDo u want to swap letters? press <n> to keep letters or any button to continue:\n"<<endl;
cin>>n;
while (n != exist)
{
cout<<"\nWhat is the letter you want to swap?\n"<<endl;
cin>>a;
cout<<"\nWhat is the letter you want to swap it with?\n"<<endl;
cin>>b;
if (inFile.is_open())
{
while (inFile.good())
{
inFile.get(c);
if( c == b )
{
outFile<< a;
}
else if (c == a)
{
outFile<< b;
}
else
{
outFile<< c;
}
}
}
else
{
cout<<"Please run the decrypt."<<endl;
}
cout<<"\nAnother letter? <n> to stop swapping\n"<<endl;
cin>>n;
}
Consider a different approach.
Collect all the character swaps in a lookup table. By default
translate['a'] == 'a', the input character is the same as the output character. To swapawithzjust settranslate['a'] = 'z'andtranslate['z'] = 'a'.Then perform a single pass over the file, copying and translating at the same time.