字符串下标超出范围C++:调试

String Subscript Out Of Range C++: Debug

本文关键字:C++ 调试 范围 下标 字符串      更新时间:2023-10-16

所以我正在调试一个运行时错误。"字符串下标超出范围"。

我知道问题出在哪里,是什么原因造成的,但我正在寻找一种可能的解决方案,它将以类似或相同的方式运行,而不会给我错误。

以下是错误发生位置的代码片段。如果我错了,请纠正我,因为我声明了一个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 ("");
}

Btw对于感兴趣的人来说,问题在这一行:

if (isalpha(nbstr[idx-1])

在这一点上,nbstr是一个长度为3的字符串,idx的值(我的程序的工作方式)总是9或10。

正如退役忍者提到的,应该在使用字符串::find函数后进行检查。