【发布时间】:2017-04-07 08:32:49
【问题描述】:
我有一个类(数组),请参见下面的 ctor。我想创建方法 Array::read(_str) 来为 Array 的对象提供在接口中键入的数组。 (例如字符串 _str = "1 2 3")
为了确定字符串应该转换成的双精度数,我正在计算空格的数量。正确找到了空格,但循环不会在最后一个空格之后结束。 (见输出屏幕文本)。
为什么找到两个空格后循环没有结束??
ctor 数组
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 ;
}
}
方法数组::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 ,因此循环仅由步骤条件结束。
【问题讨论】:
-
请告诉我们您如何使用这个
Array对象,最好创建一个Minimal, Complete, and Verifiable Example。此外,您显示的输出与您显示的代码不匹配。你期望什么输出? -
> 有没有办法检查输入的_str是否真的包含数字?
-
std::stod(and friends) 函数可能是一个好的开始。可以在循环中用于从字符串中提取以空格分隔的数字,同时还可以验证 是否 是一个有效数字。
标签: c++ arrays while-loop size-t