gpt4 book ai didi

c++ - 抛出 'std::out_of_range' what()实例后,c++终止调用:basic_string::substr:

转载 作者:行者123 更新时间:2023-12-02 10:24:29 29 4
gpt4 key购买 nike

运行时出现此错误:

抛出'std::out_of_range'实例后调用终止
what():basic_string::substr:

我是新手,任何其他提示也将不胜感激。

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

最佳答案

您试图在最后一个索引之后到达索引,则需要将循环条件更改为:
position < name.length()
并且您可以使用for循环解决此问题,该循环更可用于解决此类问题,您只需将while循环替换为:

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

使用此方法,您既不需要使用 substr()方法,也不需要使用 string letter

关于c++ - 抛出 'std::out_of_range' what()实例后,c++终止调用:basic_string::substr:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49375258/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com