Reputation: 19
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;
}
Upvotes: 1
Views: 34279
Reputation: 66
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
.
Upvotes: 3
Reputation: 8961
In your loop, position
will increase to a number equal to the characters entered by the user (i.e. "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())
Upvotes: 0