2014-04-18 2 views
3

다음 코드에서 사용자가 올바른 입력을 제공 할 때까지 루프를 실행하고 싶습니다. 그러나 시도했을 때 논스톱 루프가되었습니다.
Please Enter Valid Input.
while 루프가 없어도 동일합니다. while 루프 여기잘못된 입력에 대한 std :: cin 무한 루프

: while 루프없이 여기

#include <iostream> 
#include <fstream> 
#include <string> 
#include <ctime> 
#include <sstream> 
using namespace std; 

class library { 
public: 
    library() { 
     int mainOption; 

     cout<<"Please choose the option you want to perform."<<endl; 
     cout<<"1. Member Section"<<"\n"<<"2. Books, Lending & Donate Section"<<"\n"<<"3. Returning Section"<<endl; 
     bool option=true; 
     while (option==true) { 
      cin>>mainOption; 
      if (mainOption==1) { 
       cout<<"section 1"<<endl; 
       option=false; 
      } else if (mainOption==2) { 
       cout<<"section 1"<<endl; 
       option=false; 
      } else if (mainOption==3) { 
       cout<<"section 1"<<endl; 
       option=false; 
      } else { 
       cout<<"Please Enter Valid Input. "<<endl; 
       //option still true. so it should ask user input again right? 
      } 
     } 
    } 
}; 

int main(int argc, const char * argv[]) 
{ 
    library l1; 
    return 0; 
} 

. 그러나 똑같은 일이 일어나고 있습니다.

#include <iostream> 
#include <fstream> 
#include <string> 
#include <ctime> 
#include <sstream> 
using namespace std; 

class library { 
public: 
    library() { 
     int mainOption; 

     cout<<"Please choose the option you want to perform."<<endl; 
     cout<<"1. Member Section"<<"\n"<<"2. Books, Lending & Donate Section"<<"\n"<<"3. Returning Section"<<endl; 

     cin>>mainOption; 
     if (mainOption==1) { 
      cout<<"section 1"<<endl; 
     } else if (mainOption==2) { 
      cout<<"section 1"<<endl; 
     } else if (mainOption==3) { 
      cout<<"section 1"<<endl; 
     } else { 
      cout<<"Please Enter Valid Input. "<<endl; 
      library();//Calling library function again to input again. 
     } 
    } 
}; 

int main(int argc, const char * argv[]) 
{ 
    library l1; 
    return 0; 
} 
+2

정상적인 기능처럼 생성자를 사용하지 마십시오. – clcto

+0

@clcto 매개 변수가있는 계약자를 사용해야합니다. – IamBatman

+1

생성자는 객체의 초기 상태를 설정하는 데 사용됩니다. 이 모든 것은 실제로 void run() 함수에 있어야합니다. 당신은 이것을위한 대상조차 필요하지 않습니다. – clcto

답변

4

문제는 당신이

cin>>mainOption; // mainOption is an int 

를 호출하지만 사용자가 을 수행하지 않을 때intcin 이전 상태에서 입력 버퍼 잎 입력한다는 것입니다. 코드가 입력의 유효하지 않은 부분을 사용하지 않으면 최종 사용자가 입력 한 잘못된 값이 버퍼에 남아있어 무한 반복이 발생합니다. 당신의 while 루프가 손에서 작업을 처리 할 수있을만큼 좋기 때문에 나는 또한, 재귀를 제거

} else { 
    cout<<"Please Enter Valid Input. "<<endl; 
    cin.clear(); // Clear the error state 
    string discard; 
    getline(cin, discard); // Read and discard the next line 
    // option remains true, so the loop continues 
} 

참고 : 여기에

는이 문제를 해결하는 방법입니다.