size_t 我< _str.length在C ++中创建无限循环

size_t i < _str.length creates endless loop in c++

本文关键字:创建 无限循环 length str lt size      更新时间:2023-10-16

我有一个类(数组),请参见下面的CTOR。我想创建方法数组:: read(_str),以给出一个数组的对象,键入接口中的数组。(例如字符串_str =" 1 2 3")

要确定应将字符串转换为二倍的数量,我正在计算空间的数量。这些空间正确找到,但是循环在最后一个空间后不会结束。(请参阅输出屏幕文本)。

为什么循环在找到两个空间后都没有结束??

ctor数组

Array::Array(int _size)
{
    //ctor
    length = _size ;
    myArray = new double[length] ; // initialize array
    //default initialization
    for(size_t i = 0; i < length; i++)
    {
        myArray[i] = i ;
    }
}

方法数组:: read(String _str)

void Array::read(string _str)
{
    // string_t find (<what to search>, <starting pos>) const ;
    // determine length (number of numbers)
    length = 0 ;
    int steps = 0 ;
    size_t i = 0 ;
    cout<<"Value of _str.length() : "<<_str.length() <<endl ; // test
    while( i < _str.length() && steps < 100)
    {
        // search for space starting it i
        i = _str.find(" ",i ) ;
        if(i!=string::npos) // npos is greatest possible size_t
            cout<<"_ found at: 1 =  "<< i <<endl ;
        length ++ ;     // new number present
        i ++ ;          // next time start after space
        steps ++ ;      // to prevent endless loop
    }
    cout<<endl<<steps ;
    delete[] myArray ; // free old array
    myArray = new double[length] ; // allocate space
    // fill with doubles

}

输出屏幕文本

Value of _str.length() : 5
_ found at: i = 1
_ found at: i = 3
_found at: i = 1
_found at: i = 3

这是重复的,直到100为止,因此循环仅以步骤条件结束。

string::npos定义为size_t的最大值。

const size_t npos = -1;

当您找到字符时,i等于npos。然后,您将其添加到它,然后溢出,成为0

作为解决方案,请尝试以下操作:

if (i != string::npos) {
    // ...
    i++;
}

如果 string::find返回 string::npos

,则需要打破循环
while( i < _str.length() && steps < 100)
    {
        // search for space starting it i
        i = _str.find(" ",i ) ;
        if(  i==string::npos )
            break;
        else // npos is greatest possible size_t
            cout<<"_ found at: 1 =  "<< i <<endl ;
        length ++ ;     // new number present
        i ++ ;          // next time start after space
        steps ++ ;      // to prevent endless loop
    }

我刚刚发现,如果我将循环更改为:

while( i < _str.length() && steps < 100)
    {
        // search for space starting it i
        i = _str.find(" ",i ) ;
        if(i!=string::npos) // npos is greatest possible size_t
        {
            cout<<"_ found at: 1 =  "<< i <<endl ;
            length ++;
            i ++ ;          // next time start after space
        }

        steps ++ ;      // to prevent endless loop
    }

该功能确实给出了正确的结果。(找到3个步骤,2个空间)谢谢您的quich回复!