size_t i< _str.length在c ++中创建无限循环

时间:2016-11-23 11:02:18

标签: c++ arrays while-loop size-t

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

要确定要转换为字符串的双精度数,我计算空格量。找到正确的空格,但循环不会在最后一个空格后结束。 (见输出屏幕文字)。

  

为什么在找到两个空格之后循环不会结束?

ctor Array

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 ;
    }
}

方法Array :: 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,因此循环仅以步骤条件结束。

3 个答案:

答案 0 :(得分:4)

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

const size_t npos = -1;

如果找不到任何字符,i等于npos。然后你向它添加一个,它溢出,变成0

作为解决方案,试试这个:

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

答案 1 :(得分:1)

如果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
    }

答案 2 :(得分:0)

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

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个空格) 感谢您的回应!