繁体   English   中英

问题 - 在抛出'std::out_of_range' what() 实例后调用 C++ 终止:basic_string::substr:?

[英]Question - c++ terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr:?

我是编码新手,并试图创建一个程序来根据 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;
    }
}

看起来您误解了 string::at 的含义。

考虑以下几行:

int pos = map.at(i);
output += word.at(pos) + 'a';

at只是返回字符串中位置i处字符的 ASCII 值。 假设i为零,这是 'z',其 ASCII 值为 122。

然后尝试在word查找位置 122 处的字符, word没有那么多字符。 我不确定你到底想做什么,但事实并非如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM