Question

So I am debugging a runtime error I am getting. "string subscript out of range".

I know where the problem is and what is causing it, yet I am looking for a possible solution that will perform in a similar or identical manner without giving me the error.

Here is the code snippet to where the error occurs. Correct me if I am wrong, the problem is occurring because I am declaring a 0 length string then trying to manipulate an nth element.

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 ("");
}
Was it helpful?

Solution

Btw for whoever is interested the problem was at this line:

if (isalpha(nbstr[idx-1])

At this point nbstr is a string of length 3 and idx' value, the way my program works, is always either 9 or 10.

Also as Retired Ninja mentioned checks should be done after using the string::find function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top