自从我开始使用 XOR 运算符和简单的单字符密钥加密以来,我遇到了从未见过的问题。在第二次运行程序后,文本总是在其末尾有一个随机的 ascii 字符。另一个问题是文本“预购”和“后购”在程序每次迭代后交替修改。我敢肯定,这大部分只是由于初学者的错误,尤其是在这些问题出现的方式上缺乏 IO 经验。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream ifile;
ofstream ofile;
string toProc;
string file;
char key = ' ';
cout << "Enter file location: \n";
cin >> file;
cout << "Enter key: \n";
cin >> key;
ifile.open(file);
if(ifile.is_open())
{
char temp;
temp = ifile.get();
toProc.push_back(temp);
while(ifile.good())
{
temp = ifile.get();
toProc.push_back(temp);
}
ifile.close();
}
else
{
cout << "No file found.\n";
}
cout << "Pre action: " << toProc << endl;
for(int i = 0; i < toProc.size(); i++)
toProc[i] ^= key;
cout << "Post action: " << toProc << endl;
ofile.open(file);
ofile << toProc;
ofile.close();
}