开发者

Basic question, error: substr out of range

So I'm writing a program and part of it is to deal with an array of strings, and from each element in the strin开发者_开发问答g array, I am trying to take out every bi-gram within the string and place that in another array. I am trying to do this by using the substr function and have tried to tweak it but I continue to get an OOR error.

the code reads:

"numwords" is the number of words in the string array and "lowpunct" is the array of strings

for(i=0; i<numwords;i++)
{                
    for(x=0; x<=lowpunct[i].length()-2;x++)
    {
        if(lowpunct[i].length()-2 <=0)
        {
            bigram[count]=lowpunct[i];
            count++;
        }
        else
        {
            bistring=lowpunct[i].substr(x,2);
            bigram[count]=bistring;
            count++;
            bistring="";
        }
    }
}


string::length() is a size_t which is unsigned, so

if(lowpunct[i].length()-2 <=0)

will be a problem when a string with a length less than 2 is encountered. This is because the result of underflowing an unsigned integer is that the number wraps around at the highest value. The for loop conditional is also wrong.

Rewrite them something like this:

 for(x=0; x+2 <= lowpunct[i].length();x++)
 if(lowpunct[i].length() <= 2)


In your loop you are going from 0 to lowpunct[i].length()-2. (including the size-2). That means that there is only 1 character left. Change the "<=" in the for loop to just be "<".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜