2016-11-23 13 views
0

클래스 (배열)가 있습니다. 아래 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::findstring::npos을 반환하는 경우

+1

이 'Array' 객체를 어떻게 사용하는지 보여 주시고, [최소, 완료 및 검증 가능한 예제] (http://stackoverflow.com/help/mcve)를 만드십시오. 또한 표시되는 출력이 표시 한 코드와 일치하지 않습니다. 그리고 예상되는 결과는 무엇입니까? –

+0

> 입력 _str에 실제로 숫자가 포함되어 있는지 확인하는 방법이 있습니까? – Wietske

+0

['std :: stod' (및 친구들)] (http://en.cppreference.com/w/cpp/string/basic_string/stof) 함수가 좋은 시작일 수 있습니다. 문자열에서 공백으로 구분 된 숫자를 추출하는 루프에서 사용할 수 있으며 유효 숫자가 * 유효한지 확인합니다. –

답변

1

당신은 루프를 중단해야합니다

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::npossize_t의 가능한 최대 값으로 정의된다.

const size_t npos = -1; 

더 문자를 찾을

, inpos 같다. 그런 다음 하나를 추가하면 오버플로되어 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 
    } 

기능은 올바른 결과를 제공 않습니다

if (i != string::npos) { 
    // ... 
    i++; 
} 
0

난 그냥에 루프를 변경하면 것을 알아 냈다. (3 단계, 2 공백을 발견) quich 응답 주셔서 감사합니다!