【发布时间】:2018-03-20 02:05:01
【问题描述】:
运行时出现此错误:
在抛出 '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的值。 -
position + 1在最后三个迭代中越界。你有很多东西要学,包括如何正确地迭代具有 0 索引的东西。此外,如果您只想要一封信,请使用name[position]。建议获取good book。 -
要遍历
string中的值,请使用基于范围的for循环,例如for( char const ch: name )。请注意,这些值是编码值,对于通常的 UTF-8 编码,仅当这些字符在 ASCII 子集中时才对应于这些字符。不幸的是,C++ 库中没有直接支持迭代 characters 或推进一个字符,但是使用 UTF-8 这很容易实现,并且您使用字符串表示字符的方法是明智的,然后你会像你一样使用普通的for循环。
标签: c++