多次交换文件中的字符

Swapping chars in a file, multiple times

本文关键字:字符 文件 交换      更新时间:2023-10-16

我有工作的代码,但只有一次。我需要一个输入字符a和一个输入字符b交换。在第一次循环中,它很好地交换了两个选定的字符,但是在第二次和之后的迭代中,它除了保持outFile不变外什么也不做。我如何交换两个以上的字符,直到我想停止?

ifstream inFile("decrypted.txt");   
ofstream outFile("swapped.txt");
const char exist = 'n';
char n = '';
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 swappingn"<<endl;
    cin>>n;
}

考虑不同的方法。

收集查找表中的所有字符交换。默认情况下,translate['a'] == 'a'的输入字符与输出字符相同。要将az交换,只需设置translate['a'] = 'z'translate['z'] = 'a'

然后对文件执行一次遍历,同时复制和翻译。

#include <array>
#include <fstream>
#include <iostream>
#include <numeric>
int main()
{
    std::array<char,256> translate;
    std::iota(translate.begin(), translate.end(), 0); // identity function
    for (;;)
    {
        char a, b;
        std::cout << "nEnter ~ to end input and translate filen";
        std::cout << "What is the letter you want to swap? ";
        std::cin >> a;
        if (a == '~') break;
        std::cout << "What is the letter you want to swap it with? ";
        std::cin >> b;
        if (b == '~') break;
        std::swap(translate[a], translate[b]); // update translation table
    }
    std::ifstream infile("decrypted.txt");
    std::ofstream outfile("swapped.txt");
    if (infile && outfile)
    {
        std::istreambuf_iterator<char> input(infile), eof;
        std::ostreambuf_iterator<char> output(outfile);
        // this does the actual file copying and translation
        std::transform(input, eof, output, [&](char c){ return translate[c]; });
    }
}

您已经读取了整个文件,因此不会读取更多字节或写入更多字节。您可以使用seek返回到开头,或者直接关闭并重新打开文件。