[英]C++ Error: String subscript out of range
我為我的密碼學類編寫了一些代碼,它在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;
}
您的代碼假定純文本文件和密碼文件中的行長度相同。 特別是考慮到密碼是二進制而不是文本(從其.bin擴展名判斷),這並不是一個好的假設。 如果密碼“行”比明文行短,則會出現錯誤。
此外,密鑰始終為零長度,因此對它的每次寫入都超出范圍。 您需要使用push_back
或首先調整字符串的大小。
operator []不增加字符串長度。
key[x] =
將調用未定義的行為,在這種情況下,這是超出范圍的錯誤。 您想要的是追加或+ =。
您還假設line和cipherLine的長度相同(可能合理,也可能不合理)。 無論如何,您應該檢查一下。
第二個循環是獲取line2
,但增加到line.length()
。 應該是line2.length()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.