【问题标题】:String Subscript Out Of Range C++: Debug字符串下标超出范围 C++:调试
【发布时间】:2013-12-11 17:05:33
【问题描述】:

所以我正在调试我遇到的运行时错误。 “字符串下标超出范围”。

我知道问题出在哪里以及导致问题的原因,但我正在寻找一种可能的解决方案,该解决方案将以相似或相同的方式执行而不会出现错误。

这是发生错误的代码 sn-p。如果我错了,请纠正我,出现问题是因为我声明了一个长度为 0 的字符串,然后尝试操作第 n 个元素。

std::string VsuShapeLine::GetRunwayNumber()
{
    std::string name, nbstr, newnbstr, convnbstr;
    int idx,idx2, num, count, pos;
    char buf[3];
    int idx3=-1;
    name = this->GetName();
    idx = name.find("ALight");
    if (idx == -1)
    {
        idx = name.find("Lights");
        idx3 = name.find_last_of("Lights");
    }
    idx2 = name.find('_');
    idx2 +=3;

    nbstr = name.substr(idx2, idx-idx2);

    if (idx3 != -1)
        idx3++;
    else
        idx3 = idx+6;

    if (name.at(idx3) == 'N')
    {
        pos = nbstr.length();
        if (isalpha(nbstr[idx-1]))
            nbstr[pos-1] = _toupper(nbstr[pos-1]);
        return (nbstr);
    }

    else if (name.at(idx3) == 'F')
    {
        convnbstr = nbstr.substr(0,2);
        num = atoi(convnbstr.data());
        num +=18;
        _itoa(num, buf, 10);
        newnbstr = buf;
        count = nbstr.size();

        if (count > 2)
        {
            if (nbstr.at(2) == 'l' || nbstr.at(2) == 'L')
                newnbstr += 'r';

            else if (nbstr.at(2) == 'r'|| nbstr.at(2) == 'R')
                newnbstr += 'l';

            else if (nbstr.at(2) == 'c' || nbstr.at(2) == 'C')
                newnbstr += 'c';
        }
        pos = newnbstr.length();
        if (isalpha(newnbstr[pos-1]))
            newnbstr[pos-1] = _toupper(newnbstr[pos-1]);
        return (newnbstr);
    }

    return ("");
}

【问题讨论】:

  • 也许您可以向我们展示idx 的设置,因为这似乎是您的问题。
  • 如果这是你的全部代码并且字符串确实是空的,你不能索引到它。
  • 你....在声明它和尝试索引它之间对nbstr 做任何事情吗?如果pos 为0,那么nbstr[pos-1] 肯定会让运行时开始运行。
  • 是的,在声明和其他 3 行之间有一个完整的函数,我应该发布整个内容吗?
  • 是的,发布所有相关代码。

标签: c++ string debugging assertions


【解决方案1】:

顺便说一句,任何对这个问题感兴趣的人都在这一行:

if (isalpha(nbstr[idx-1])

此时 nbstr 是一个长度为 3 和 idx' 值的字符串,我的程序的工作方式始终是 9 或 10。

正如 Retired Ninja 提到的,应该在使用 string::find 函数后进行检查。

【讨论】:

    猜你喜欢
    • 2013-04-22
    • 2012-04-27
    • 1970-01-01
    • 2015-03-31
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多