Apparently, when my code reaches this if statement, a string subscript out of range exception occurs.

// a is int
// str is std::string

while ( true )
{    
// other stuff
if( a == str.size() ) // this line throws an exception
    break;
}

In what case can such a simple if-statement throw an exception? I just don't see it. Shouldn't it simply return 0 if for some reason the comparison fails?

EDIT: This is the full function in which it occurs. It basically reads through a file and takes in the value of some tokens of its. And if it is of some relevancy, I'm using Visual Studio 2010 Express and the error says "Debug Assertion Failed".

void Function(string &str, int start)
{
    int outline;

    // Read all attributes
    int pos, pos2 = start;
    while( true )
    {       
        pos = SkipWhiteSpace(str, pos2);
        pos2 = FindEndOfToken(str, pos);

        string token = str.substr(pos, pos2-pos);

        pos = SkipWhiteSpace(str, pos2);
        if( pos == str.size() || str[pos] != '=' ) break;

        pos = SkipWhiteSpace(str, pos+1);
        pos2 = FindEndOfToken(str, pos);
        file<<"...part 3";

        string value = str.substr(pos, pos2-pos);

        if( token == "outline" )
            outline = (short)strtol(value.c_str(), 0, 10);

        if( pos == str.size() ) // <--- error here (at least, it seems so)
            break;      
    }

    SetOutline(outline);
}

And the SkipWhiteSpace() and FindEndOfToken() functions are these two.

int SkipWhiteSpace(string &str, int start)
{
    UINT n = start;
    while( n < str.size() )
    {
        char ch = str[n];
        if( ch != ' ' && 
            ch != '\t' && 
            ch != '\r' && 
            ch != '\n' )
            break;

        ++n;
    }

    return n;
}

int FindEndOfToken(string &str, int start)
{
    UINT n = start;
    if( str[n] == '"' )
    {
        n++;
        while( n < str.size() )
        {
            char ch = str[n];
            if( ch == '"' )
            {
                // Include the last quote char in the token
                ++n;
                break;
            }
            ++n;
        }
    }
    else
    {
        while( n < str.size() )
        {
            char ch = str[n];
            if( ch == ' ' ||
                ch == '\t' ||
                ch == '\r' ||
                ch == '\n' ||
                ch == '=' )
                break;

            ++n;
        }
    }

    return n;
}
有帮助吗?

解决方案

This line can never throw an exception. Are you sure what you get is a real C++ exception and not a crash?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top