Reputation: 222
So, this returns an error on execution, no errors shown in the debugger.
Debug assertion failed!
Expression: String subscript out of range.
For information on how your program can couse an assertion failure, see the visual c++ documentation on asserts.
int main()
{
// declaring variables
string input = "";
int firstChar;
// process:
cout << "Please enter a valid sentence (with spaces):\n>";
getline(cin, input);
cout << "first char is " + input[0] << endl << endl;
firstChar = input.length();
cout << "last char is " + input[firstChar];
// stop and return success
getchar();
return 0;
}
Upvotes: 0
Views: 184
Reputation: 96835
input[firstChar]
is attempting to access the byte one-pass the end of the character array input
because arrays are indexed by [0, length)
.
The last character is actually input[firstChar - 1]
.
Just a little tip, use the stream insertion operator <<
instead of +
because the latter yeilds a temporary std::string
object.
Upvotes: 1
Reputation: 482
You should test that in your input
is a valid content before using it.Something like if(length(input)>0)...
.The user might not give the wanted data even if you typed what you need between () and validations are needed
Upvotes: 0
Reputation: 18226
C++ strings of length length
are indexed from 0
to length - 1
.
Upvotes: 5