问题 - 在抛出 'std::out_of_range' what(): basic_string::substr:? 的实例后调用 C++ 终止
Posted
技术标签:
【中文标题】问题 - 在抛出 \'std::out_of_range\' what(): basic_string::substr:? 的实例后调用 C++ 终止【英文标题】:Question - c++ terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr:?问题 - 在抛出 'std::out_of_range' what(): basic_string::substr:? 的实例后调用 C++ 终止 【发布时间】:2020-03-23 17:26:49 【问题描述】:我是编码新手,我正在尝试创建一个基于 26 个字符的映射来加密/解密的程序。代码的加密部分有效,但每当我尝试解密时,我都会收到错误
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 122) >= this->size() (which is 5).
我该怎么办?
#include <iostream>
#include <cstring>
using namespace std;
string encrypt(string word, string map = "zyxwvutsrqponmlkjihgfedcba")
string output = "";
for(int i = 0; i < word.length(); i++)
int pos = word.at(i) - 'a';
output += map.at(pos);
return output;
string decrypt(string word, string map = "zyxwvutsrqponmlkjihgfedcba")
string output = "";
for(int i = 0; i < word.length(); i++)
int pos = map.at(i);
output += word.at(pos) + 'a';
return output;
int main()
string method, word, map;
cout << "What is the method (encryption or decryption)? ";
cin >> method;
if(method.compare("encryption") != 0 && method.compare("decryption") != 0)
cout << "Error: invalid method choice.\n";
return 0;
cout << "What is the translation map (type 'default' to use default): ";
cin >> map;
if(map.compare("default") && method.length() != 26)
cout << "Error: invalid translation map size.\n";
return 0;
cout << "What is the single word to translate: ";
cin >> word;
if(method.compare("encryption") == 0)
for(int i = 0; i < word.length(); i++)
if(!isalpha(word.at(i)) || !islower(word.at(i)))
cout << "Error: encryption cannot be performed.\n";
return 0;
if(map.compare("default") == 0)
cout << "Encrypted word: " << encrypt(word) << endl;
else
cout << "Encrypted word: " << encrypt(word, map) << endl;
if(method.compare("decryption") == 0)
if(map.compare("default") == 0)
map = "zyxwvutsrqponmlkjihgfedcba";
for(int i = 0; i < word.length(); i++)
if(map.find(word.at(i)) == string::npos)
cout << "Error: decryption cannot be performed." << endl;
return 0;
if(map.compare("default") == 0)
cout << "Decrypted word: " << decrypt(word) << endl;
else
cout << "Decrypted word: " << decrypt(word, map) << endl;
【问题讨论】:
哦,请,请,缩进。但是what()
文本几乎可以准确地告诉您问题所在。您正在尝试访问 5 个字符的字符串中的字符 122。
【参考方案1】:
看来你误解了 string::at 的意思。
考虑以下几行:
int pos = map.at(i);
output += word.at(pos) + 'a';
at
只是将字符串中i
位置处的字符的 ASCII 值返回给您。假设i
为零,这是 'z',其 ASCII 值为 122。
然后您尝试查找word
中位置122 的字符,word
没有那么多字符。我不确定你到底想做什么,但不是那样。
【讨论】:
谢谢贾斯珀!感谢您的意见。以上是关于问题 - 在抛出 'std::out_of_range' what(): basic_string::substr:? 的实例后调用 C++ 终止的主要内容,如果未能解决你的问题,请参考以下文章
在抛出 'std::system_error 的实例后调用终止