我有一个类(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)函数可能是一个好的开始。可用于循环从字符串中提取空格分隔的数字,同时还验证*是*有效数字。 –