[英]cin.fail while loop input Re-Entry
僅嘗試檢查輸入是否是此問題的布爾變量(1或0)。
但是,無論何時觸發while循環(即,不輸入1或0),它都會掉下來並說條件成立。
我希望用戶能夠在輸入錯誤之后重新輸入他們的輸入。 我將如何去做呢?
我的代碼:
int main() {
bool a,b,c;
cout << "This program will determine the value of the condition !(a||b) && c " << endl;
cout << "Please enter boolean values for a, b, and c. (0=F, 1=T) ";
cin >> a;
while (cin.fail())
{
cin.ignore(1000,'|n');
cin.clear();
cout << "Error: Enter only 0 or 1" << endl;
cout << "Enter in a new value for a" << endl;
}
cin >> b;
cin >> c;
cout << "The condition !(xx||xx)&&xx ";
if(!(a||b) && c)
{
cout << "is true";
}
else
{
cout << "is false";
}
return 0;
}
您需要輸入cin >> a;
在while循環的末尾。
cin.clear()
將消除錯誤,然后while循環將停止。
像這樣:
cin >> a;
while (cin.fail())
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Error: Enter only 0 or 1" << endl;
cout << "Enter in a new value for a" << endl;
cin >> a;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.