我在 C++ "out_of_range at memory location"有问题

i have a problem "out_of_range at memory location" in c++

本文关键字:memory 有问题 location at of C++ out 我在 range      更新时间:2023-10-16
#include<iostream>
#include<string>
using namespace std;
int main()
{
string pumbaTheString;
getline(cin, pumbaTheString);
int indexs[3];
for (int i = 0; i < 3; ++i)
{
indexs[i] = pumbaTheString.find(" ");
pumbaTheString.replace(indexs[i], 1, "*");
}
cout << pumbaTheString << endl;
pumbaTheString.replace(indexs[2] + 1, (pumbaTheString.length() - indexs[2]), "#!!@1234");
cout << pumbaTheString<<endl;
for (int i = 0; i < 3 ; ++i)
{
pumbaTheString =  pumbaTheString.substr((indexs[i] - indexs[i - 1]), pumbaTheString.length());//here its did the problem
cout << pumbaTheString << endl;
}
system("pause");
return 0;
}

项目1.exe中0x75CCAD12处未处理的异常: Microsoft C++例外:内存位置 0x0073F614 处的 std::out_of_range。发生

for循环的第一次迭代中,您正在尝试获取indexs[i - 1] == indexs[-1]元素。数组索引从 0 开始,禁止使用负值。您需要为第一次迭代添加一些特殊处理,例如:

for (int i = 0; i < 3 ; ++i)
{   
if(i == 0)
{
// special handling
}
else
{
pumbaTheString =  pumbaTheString.substr((indexs[i] - indexs[i - 1]), pumbaTheString.length());//here its did the problem
}
cout << pumbaTheString << endl;
}