我正在尝试设计一个程序,它将打开任何文本文件,将其读入字符串,用 XOR 加密字符串,并将字符串写入新的文本文件。下面的代码有效,但会产生多个“系统哔声”。
我的疯狂猜测是我没有正确处理空格?我不确定。任何想法我做错了什么?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
ofstream outFile;
// Define variables
string fileName,
key = "seacrest out";
// Input
cout << "Please enter the name of the file you wish to encrypt: ";
cin >> fileName;
cout << endl;
inFile.open(fileName, ios::in | ios::binary);
string str((istreambuf_iterator<char>(inFile)), istreambuf_iterator<char>()); // Reads a text file into a single string.
inFile.close();
cout << "The file has been read into memory as follows:" << endl;
cout << str << endl;
system("pause");
// Encryption
cout << "The file has been encrypted as follows:" << endl;
for (unsigned x = 0; x < str.size(); x++) // Steps through the characters of the string.
str[x] ^= key[x % key.size()]; // Cycles through a multi-character encryption key, and encrypts the character using an XOR bitwise encryption.
cout << str << endl; // This code works, but I get system beeps. Something is still wrong.
// Write Encrypted File
cout << "Please enter the file name to save the encrypted file under: ";
cin >> fileName;
cout << endl;
outFile.open(fileName, ios::out | ios::binary);
outFile.write(str.c_str(), str.size()); // Writes the string to the binary file by first converting it to a C-String using the .c_str member function.
system("pause");
return 0;
}