我试图为我的项目做一个密码,我发现了getline的一个错误,因为我希望用#39;来填充字符串。'但是当我输入“'。'错误显示" Mini-Project.exe中的0x77031D4D处的未处理异常:Microsoft C ++异常:内存位置0x00C6F478处的std :: out_of_range。"我已经试图修复这个错误数周,但我不能。请告诉我我的错误。我很乐意学习新的代码方法。感谢。
#include <iostream>
#include <string>
using namespace std;
class Encryption
{
private:
string encrypt;
string decrypt;
public:
Encryption();
Encryption(string,string);
void set_encryption(string&);
string encryption();
void set_decryption(string);
string decryption();
};
Encryption::Encryption()
{
encrypt = "";
decrypt = "";
}
Encryption::Encryption(string Encrypt,string Decrypt)
{
encrypt = Encrypt;
decrypt = Decrypt;
}
void Encryption::set_encryption(string &Encrypt)
{
encrypt = Encrypt;
}
string Encryption::encryption()
{
char a;
string text1(encrypt);
for (int i = 0; i <= encrypt.size() - 1; i++)
{
a = encrypt.at(i);
int b = (int)a;
b += 1;
//if (b > 254) { b = 254; }
a = (char)b;
text1.insert(i, 1, a);
}
string Encrypted(text1, 0, encrypt.size());
encrypt = Encrypted;
return encrypt;
}
void Encryption::set_decryption(string Decrypt)
{
decrypt = Decrypt;
}
string Encryption::decryption()
{
char c;
string text2(decrypt);
for (int i = 0; i <= (decrypt.size() - 1); i++)
{
c = decrypt.at(i);
int d = (int)c;
d -= 1;
c = (char)d;
text2.insert(i, 1, c);
}
string Decrypted(text2, 0, decrypt.size());
decrypt = Decrypted;
return decrypt;
}
int main()
{
while (1)
{
//initialize and get the string from the user
Encryption text;
char a,ans,text1c;
string text1, text2;
do
{
cout << "****Welcome to Subition Cpiher****" << endl;
cout << "This Program Only Allow Alphabet." << endl;
cout << "Please Enter \n1-Encrypt \n2-Decrypt\n3-Clear Screen \n0-End " << "\n:";
cin >> a;
}
while (a != '1' && a != '2' && a != '0' && a!='3');
if (a == '1')
{
again:char c;
cout << "Enter a string to encrypt <End with '.'>: ";
getline(cin, text1, '.');
c = text1.at(1);
if (c == '.')
{
cout << "You have not enter any string. Please try again." << endl;
goto again;
}
else
{
text1.erase(text1.begin());
text.set_encryption(text1);
cout << "The encrypted text is: " << text.encryption() << endl;
}
}
else if (a == '2')
{
cout << "Enter a string to decrypt <End with '.'>: ";
getline(cin, text2, '.');
text2.erase(text2.begin());
text.set_decryption(text2);
cout << "The decryted text is: " << text.decryption() << endl;
}
else if (a == '0')
{
cout << "Thank you for using the software." << endl;
system("pause");
return 0;
}
else if (a == '3')
{
system("cls");
}
}
}
答案 0 :(得分:0)
替换
c = text1.at(1); if(c ==&#39;。&#39;)
与
if(text1.size()== 1)
当你把。你有一个带有空字符串的1个元素的数组,并尝试做text1.at(1)这个读取一个不存在的内存块所以不要这样做。
玩得开心