gpt4 book ai didi

c++ - 输入句子时终止std::out_of_range

转载 作者:行者123 更新时间:2023-12-02 10:14:04 26 4
gpt4 key购买 nike

这段代码是关于将字符串转换为替代密码(将特定字母替换为另一个特定字母,例如:用'E'代替'a')当我输入字符串时,它可以正常工作。但是,当我输入一个句子时,它说“在抛出一瞬间'std::out_of_range'之后,终止 call ”。这是什么呢?我该怎么办?

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main(){

string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
string key {"EFGHIJKLMNOPQRSTUVWXYZ1234efghijklmnopqrstuvwxyz5678"};
string secret_massage {};
string encrypted_massage {} ;

cout << "Enter your secret massege : ";
getline(cin, secret_massage) ;
cout << "Encrypting massage . . . " << endl;
cout << "Encrypted massege : " ;

for ( size_t i {0} ; i < secret_massage.length() ; ++i ){
char selection {};
int j {};
selection = secret_massage[i];
j = alphabet.find(selection);
encrypted_massage = key.at(j);
cout << encrypted_massage;
} [enter image description here][1]

cout << endl;
return 0;
}

最佳答案

输入句子时,句子中会有空格。但是alphabet没有空格字符( )。因此,当selection 时,您将执行以下操作:

j = alphabet.find(selection);
encrypted_massage = key.at(j);
j中的结果将是 std::string::npos,然后在 .at()中使用该值将引发 std::out_of_range异常。
您可以通过在密码中添加空格或在输入中找到空格时不进行替换来解决此问题。

关于c++ - 输入句子时终止std::out_of_range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62537514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com