在std :: string中找到最后一个字符错误:表达式:字符串下标超出范围

Joh*_*DOe 0 c++

因此,这会在执行时返回错误,调试器中不会显示错误.

调试断言失败了!

表达式:字符串下标超出范围.

有关程序如何解决断言失败的信息,请参阅有关断言的visual c ++文档.

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;
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*tti 5

长度length为C++的字符串索引0length - 1.