2016-11-23 39 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個空格) 謝謝你的反應!