简体   繁体   中英

c++ terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr:

I am getting this error when running:

terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr:

I am brand new, any other tips would be appreciated as well.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    int position = 1;
    string letter;

    cout << "Enter in your full name seperated by a space: ";
    getline (cin, name);

    cout << name.substr(0, 1);

    while (position <= name.length())
    {
        position++;
        letter = name.substr(position, 1);

        if (letter == " ")
        {
            cout << name.substr(position + 1, 1) << " ";
        }
    }

    cout << endl;

    return 0;
}

You are trying to reach an index after the last index, you need to change your loop condition to : position < name.length()

and you can solve this problem using for-loop which is more used for such problems, you just need to substitute your while-loop with :

for (int position = 0; position < (name.length()-1); position++) {
    if (name[position] == ' ') {
        cout << name[position+1];
    }
}

Using this you wouldn't need to use substr() method neither string letter .

In your loop, position will increase to a number equal to the characters entered by the user (ie "Abc Def" last loop iteration: position = 8). In this case name.substr(position, 1); tries to extract the character after the last character in your string, hence the std::out_of_range exception. You may want to change your loop condition to: while (position <= name.length() - 1) or while (position < name.length())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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