3

所以我正在编写一个程序,其中一部分是处理一个字符串数组,并且从字符串数组中的每个元素中,我试图取出字符串中的每个二元组并将其放在另一个数组中。我正在尝试通过使用 substr 函数来执行此操作,并尝试对其进行调整,但我继续收到 OOR 错误。

代码如下:

“numwords”是字符串数组中的单词数,“lowpunct”是字符串数组

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="";
        }
    }
}
4

2 回答 2

0

string::length() 是一个无符号的 size_t,所以

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

当遇到长度小于 2 的字符串时会出现问题。这是因为下溢无符号整数的结果是该数字在最大值处回绕。for 循环条件也是错误的。

像这样重写它们:

 for(x=0; x+2 <= lowpunct[i].length();x++)
 if(lowpunct[i].length() <= 2)
于 2011-04-21T03:41:51.017 回答
0

在您的循环中,您将从 0 变为 lowpunct[i].length()-2。(包括尺寸 2)。这意味着只剩下 1 个字符。将 for 循环中的“<=”更改为“<”。

于 2011-04-21T03:55:34.917 回答