多次交换文件中的字符

时间:2011-12-15 00:59:09

标签: c++ fstream

我的代码只能运行一次。我需要一个输入字符a与输入字符b交换。第一次通过循环时,它会将两个选定的字符交换为精细,但在第二次和后续迭代中,它只会使outFile保持不变。在我想要停止之前,如何交换两个以上的字符?

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;
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

考虑一种不同的方法。

收集查找表中的所有字符交换。默认情况下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 file\n";
        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]; });
    }
}