2016-11-23 93 views
0

我有一个类(Array),请参阅下面的ctor。我想要创建方法Array :: read(_str)为Array的对象提供在界面中键入的数组。 (例如string _str =“1 2 3”)size_t我<_str.length在C++中创建无限循环

要确定字符串应该转换成的双精度数,我计算空格的数量。空格被正确找到,但循环不会在最后一个空格之后结束。 (请参阅输出屏幕文本)。

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

构造函数阵列

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

方法阵列::读取(串_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,从而循环仅以步骤条件结束。

+1

请告诉我们你如何使用这个'Array'对象,最好创建一个[最小,完整和可验证的例子](http://stackoverflow.com/help/mcve)。此外,您显示的输出与您显示的代码不符。你期望什么产出? –

+0

>有没有办法来检查输入_str是否实际包含一个数字? – Wietske

+0

['std :: stod'(和朋友)](http://en.cppreference.com/w/cpp/string/basic_string/stof)函数可能是一个好的开始。可用于循环从字符串中提取空格分隔的数字,同时还验证*是*有效数字。 –

回答

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 
    } 
+0

也许使用'else'? –

+0

@appleapple没有其他部分更清楚吗? – Steephen

+0

好吧,我的意思是'if(i!= string :: npos)'=>'else'。 –

4

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

const size_t npos = -1; 

当你发现没有字符,i等于npos。然后你添加一个,它溢出,变成0

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

if (i != string::npos) { 
    // ... 
    i++; 
} 
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个空格) 谢谢你的反应!