themooncrafter
themooncrafter

Reputation: 21

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

I'm not able to pass a string to a function. Actually I can build & run my program but it gives me this error (I typed in '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)

I want to build a program being able to recognize different keywords in a question and answering

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

Additional I'm not able to pass 'result' trough the for()-loop. I read that the compiler would destroy all functions used in the for()-loop but I don't know how to fix it. Using while() neither works for me.Hope you can help me -Thank you :)

Upvotes: 1

Views: 10096

Answers (2)

Chris Jefferson
Chris Jefferson

Reputation: 7157

This loop:

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

Will, if the string contains no spaces (or no more spaces), go past the end of the string. At that point, input.at causes the exception to be thrown. You need to check if you have reached the end of your string here!

Upvotes: 1

RedX
RedX

Reputation: 15175

vector::at() will throw if you try to acces out of bounds.

The problem is that you increment pos and check for space. What if your input string does not have space?

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

Upvotes: 1

Related Questions