抛出 'std::out_of_range' what() 的实例: basic_string::at_n __n >= this->size()

throwing an instance of 'std::out_of_range' what(): basic_string::at_n __n >= this->size()

本文关键字:gt std at size this- string basic what range 抛出 out      更新时间:2023-10-16

我无法将字符串传递给函数。实际上我可以建立&运行我的程序,但是它给了我这个错误(我输入了'spoon'):

terminate called after throwing an instance of 'std::out_of_range'
  what(): basic_string::at_n __n (which is 5) >= this->size() (which is 5)
Aborted (core dumped)

我想建立一个程序能够识别不同的关键字在一个问题和回答

#include <iostream>
#include <string>
using namespace std;
int result;
//returns value of the analysation case
int analyze(string w)
{
    if(w == "knife"){return 1;}
    if(w == "spoon"){return 2;}
    if(w == "fork"){return 3;}
    return 0;
}
int main ()
{
    string input;
    cin >> input;
    for(int pos = 0; pos < input.length(); pos++) //as long the current letter is within the string
        {
            string word = "";           //resetting stored word
            while(input.at(pos) != ' ') //as long the current letter is not a space => goes trough a whole word
            {
                word += input.at(pos);  //add the current letter to the current word
                pos ++;
            }
            int result = analyze(word);    //gets word analyzation result
        }
    switch(result)
    {
        case 1:
            cout << "do something (1)"; break;
        case 2:
            cout << "do something (2)"; break;
        case 3:
            cout << "do something (3)"; break;
        default:
            cout << "I do not understand";
    }
    return 0;
}

另外,我不能通过for()循环传递'result'。我读到编译器会销毁for()循环中使用的所有函数,但我不知道如何修复它。使用while()对我来说都不起作用。希望你能帮助我-谢谢:)

vector::at()会抛出越界访问

问题是您增加pos并检查空间。如果你的输入字符串没有空格怎么办?

while(input.at(pos) != ' ') /* You should also abort when pos >= input.length() */
{
    word += input.at(pos);  //add the current letter to the current word
    pos ++;
}

这个循环:

while(input.at(pos) != ' ') //as long the current letter is not a space => goes trough a whole word
{
     word += input.at(pos);  //add the current letter to the current word
     pos ++;
}

将,如果字符串不包含空格(或没有更多空格),越过字符串的末尾。在这一点上,input.at导致异常被抛出。你需要检查你是否到达了字符串的末端!