从文件中读取并在C ++中交换某些char

时间:2011-12-13 00:33:12

标签: c++ vector replace char ifstream

在这个函数中,我需要替换输入的文件中的所有字符,例如一个a,输入另一个字符,例如i。我已经给了它两枪,但是因为我是新手而且我的大脑甚至为什么都没有建议?

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

或:

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

3 个答案:

答案 0 :(得分:4)

仔细看看这段代码:

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;

它读取两个字符,不多也不少。如果你点击“a b enter”,你就可以了,输入将是未读的,但这不会造成任何伤害 - 它会将“a”和“b”读入两个变量。但是如果你点击“输入b输入”,它将读取“a”并输入两个变量!

答案 1 :(得分:2)

我从一个相对简单的解决方案开始:

  1. 将文件内容存储在vector<char>(注意大文件)
  2. 遍历向量的内容并执行交换
  3. 使用向量
  4. 的内容覆盖旧文件

答案 2 :(得分:2)

执行此操作的一种方法是读取原始文件,替换字符并将输出写入新文件。

然后最终当你完成时可能用新的覆盖旧文件。