【问题标题】:terminating std::out_of_range while inputing a sentence输入句子时终止 std::out_of_range
【发布时间】:2020-06-23 14:45:44
【问题描述】:

此代码是关于将字符串转换为替代密码(将特定字母替换为另一个特定字母,例如:'E' for 'a')当我输入字符串时,它可以正常工作。但是当我输入一个句子时,它说'Mterminating call after throwing a moment of 'std::out_of_range''。什么是hapeening?我该怎么办?

#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;
}

【问题讨论】:

    标签: c++ string loops output c++14


    【解决方案1】:

    当你输入一个句子时,句子中有空格。但是alphabet 没有空格字符( )。所以当selection 时,你会这样做:

    j = alphabet.find(selection);
    encrypted_massage = key.at(j);
    

    j 中的结果将为std::string::npos,然后在.at() 中使用该值将引发std::out_of_range 异常。

    您可以通过在密码中添加一个空格来解决此问题,或者当您在输入中找到空格时不进行替换。

    【讨论】:

      猜你喜欢
      • 2016-07-15
      • 2021-01-02
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多