2014-04-18 41 views
3

在我的下面的代碼中,我想循環直到用戶提供了正確的輸入。但是當我嘗試它變成一個不間斷的循環。
Please Enter Valid Input.
沒有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; 
} 

這裏沒有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; 

     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葉老態的輸入緩衝區。除非您的代碼使用輸入的無效部分,否則最終用戶輸入的錯誤值將保留在緩衝區中,導致無限重複。

這裏是你如何解決這個問題:

} 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 
} 

請注意,我也去掉了遞歸,因爲你的while環是不夠好,處理手頭的任務。