我有一個類(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
,從而循環僅以步驟條件結束。
請告訴我們你如何使用這個'Array'對象,最好創建一個[最小,完整和可驗證的例子](http://stackoverflow.com/help/mcve)。此外,您顯示的輸出與您顯示的代碼不符。你期望什麼產出? –
>有沒有辦法來檢查輸入_str是否實際包含一個數字? – Wietske
['std :: stod'(和朋友)](http://en.cppreference.com/w/cpp/string/basic_string/stof)函數可能是一個好的開始。可用於循環從字符串中提取空格分隔的數字,同時還驗證*是*有效數字。 –