클래스 (배열)가 있습니다. 아래 ctor를 참조하십시오. Array Array :: Read (_str) 메서드를 만들어서 Array 객체에 인터페이스에 입력 된 배열을주고 싶습니다. (예 : string _str = "1 2 3")size_t i <_str.length는 C++에서 무한 루프를 만듭니다.
문자열을 두 개로 변환해야하는지 결정하려면 공백을 계산합니다. 공백은 정확하게 발견되지만 루프는 마지막 공백 다음에 끝나지 않습니다. (출력 화면 텍스트 참조).
왜 두 공백을 찾은 후에 루프가 끝나지 않습니까 ??
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 ;
}
}
방법 어레이 :: 판독 (문자열 _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
때까지 반복되고, 따라서 루프 단계 조건에 의해서만 종료됩니다. string::find
가 string::npos
을 반환하는 경우
이 'Array' 객체를 어떻게 사용하는지 보여 주시고, [최소, 완료 및 검증 가능한 예제] (http://stackoverflow.com/help/mcve)를 만드십시오. 또한 표시되는 출력이 표시 한 코드와 일치하지 않습니다. 그리고 예상되는 결과는 무엇입니까? –
> 입력 _str에 실제로 숫자가 포함되어 있는지 확인하는 방법이 있습니까? – Wietske
['std :: stod' (및 친구들)] (http://en.cppreference.com/w/cpp/string/basic_string/stof) 함수가 좋은 시작일 수 있습니다. 문자열에서 공백으로 구분 된 숫자를 추출하는 루프에서 사용할 수 있으며 유효 숫자가 * 유효한지 확인합니다. –