3
在我的下面的代碼中,我想循環直到用戶提供了正確的輸入。但是當我嘗試它變成一個不間斷的循環。
Please Enter Valid Input.
沒有while循環它也是一樣的。std :: cin錯誤輸入的無限循環
這裏:
#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;
}
請不要使用像他們是正常功能的構造函數 – clcto
@clcto你的意思是,我們應該使用承包商時,他們有參數? – IamBatman
構造函數用於設置對象的初始狀態。這一切都應該在'void run()'函數中。你甚至不需要這個對象。 – clcto