引发'std :: out_of_range'what()实例后调用终止方法what():basic_string

时间:2019-01-15 06:53:48

标签: c++

string word;
int l,eFound,xFound;
l = word.size();
cout <<"Enter a word: ";
cin >> word;

for (l>0 ; word.at(l)!='x' || word.at(l)!='e'; l--)
    if (word.at(l) == 'e'){
        eFound = true;
    }
    else if (word.at(l) == 'x'){
        xFound = true;
    }

if (eFound == true && xFound == true){
    cout << "Your word, "<<word<<", contains the character 'e'"<<"\n";
    cout << "Your word, "<<word<<", contains the character 'x'";
}
if (eFound == true && xFound != true){
    cout << "Your word, "<<word<<", contains the character 'e'";
}
if (xFound == true && eFound != true){
    cout << "Your word, "<<word<<", contains the character 'x'";
}

我不确定发生了什么,我正在尝试使用for循环来检测某个单词的输入中的e或x。我单击了具有相同错误的其他页面,但是它们具有不同的代码,并且我不太了解所解释的内容。那么,是什么导致此错误?我上第一门编程课已经两周了,如果我问一个愚蠢的问题,对不起。

1 个答案:

答案 0 :(得分:1)

问题是std::string的索引从零开始。不是来自1。因此,如果word.at(l)l = word.size();将崩溃。

您应将语句更改为:l = word.size() - 1;

此外,将循环条件更改为for (; l >= 0 ; l--)

建议:

请使用库功能:

赞:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string word;
    cout <<"Enter a word: ";
    cin >> word;

    bool eFound = word.find('e') != string::npos;
    bool xFound = word.find('x') != string::npos;

    if (eFound) {
        cout << "Your word, "<<word<<", contains the character 'e'" << "\n";
    }

    if (xFound) {
        cout << "Your word, "<<word<<", contains the character 'x'" << "\n";
    }

    return 0;
}