【问题标题】:i have a problem "out_of_range at memory location" in c++我在c ++中有一个问题“内存位置的out_of_range”
【发布时间】:2019-09-24 11:46:31
【问题描述】:
#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;
}

//Project1.exe中0x75CCAD12处未处理的异常: // Microsoft C++ 异常:内存位置 0x0073F614 处的 std::out_of_range。发生了

【问题讨论】:

  • indexs[i - 1] for i=0 将是 indexs[-1] 所以它超出范围
  • 除了上面提到的索引问题(这不会直接导致out_of_range异常,而是未定义的行为,这当然可能导致进一步的异常路,就像您使用不确定的值作为字符串索引一样)您确定所有的字符串操作都可以工作吗?输入中至少有三个空格?您保存在数组中的所有索引都有效吗?当您收到异常时,exact 输入是什么?
  • 不要在 C++ 中使用原始数组,至少使用std::array(或可能的std::vector),它们都在调试版本中提供越界检查。
  • 在高层次上,这段代码应该做什么?我确信有更好/更容易/更不容易出错的方法来完成你想要完成的任何事情。

标签: c++ string


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2015-08-25
    • 1970-01-01
    相关资源
    最近更新 更多