我为我的加密类编写了一些代码,它在sagemath.com终端上运行,但在visual studio 2013中没有。我不知道是什么给了我错误。我认为它与for
循环有关,但我无法弄清楚要改变什么。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream plain1("plaintext1.txt");
ifstream cipher("ciphertext1.bin");
string line, cipherLine, key;
if(plain1.is_open() && cipher.is_open())
{
getline(plain1, line);
getline(cipher, cipherLine);
for (unsigned int x = 0; x < line.length(); x++)
{
key[x] = line[x] ^ cipherLine[x];
}
}
plain1.close();
cipher.close();
ifstream cipher2("ciphertext2.bin");
ofstream plain2("plaintext2.txt");
string line2, decrypt;
if (cipher2.is_open())
{
getline(cipher2, line2);
for (unsigned int y = 0; y < line.length(); y++)
{
decrypt[y] = key[y] ^ line2[y];
plain2 << decrypt[y];
}
}
cout << "File decrypted successfully." << endl;
cipher2.close();
plain2.close();
system("pause");
return 0;
}
答案 0 :(得分:1)
您的代码假定明文和密码文件中的行长度相同。特别是考虑到密码是二进制的,而不是文本(从它的.bin扩展来判断),这不是一个好的假设。如果密码&#34;行&#34;比明文行短,你会得到错误。
此外,密钥始终为零长度,因此每次写入都是超出范围的。您需要先使用push_back
或先调整字符串大小。
答案 1 :(得分:0)
operator []不会添加字符串长度。
key[x] =
将调用未定义的行为,在这种情况下是超出范围的错误。你想要的是追加或+ =。
您还假设(可能或可能不合理)line和cipherLine的长度相同。无论如何你应该检查这个。
您的第二个循环正在获得line2
,但递增到line.length()
。它应该是line2.length()