cin.当循环输入时失败
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;
}
相关文章:
- 我应该如何在C++中使用结构体解决输入失败的问题?
- 多个输入的代码失败
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- boost::p rogram_options - 验证失败时,显示用户在错误消息中输入的值
- C++使用命令行输入 txt 文件,但打开文件失败
- Spirit X3,如何在非ASCII输入上失败
- 字符串流运算符输入失败
- C++:为什么这个字符串输入失败,而另一个没有
- std::getline(std::cin, string) 可能因键盘输入失败的方式
- 可视C 资本化功能因多个输入而失败
- c++ sort() 函数对于<algorithm>整数数组的大小(元素数)>10^7 个元素的大输入是否失败?
- FSTREAM在输入负数时失败
- 为什么我们总是检查输入是否失败而不检查输出
- C++,将输入字符串转换为数字,转换失败不应返回零
- 失败的输入帮助,国际和字符,C++
- 每当我输入长度为4的字符串时,下面的cpp代码就会崩溃(向量中的malloc失败)
- C++输入失败:单个语句中有多个输入
- C++失败的空输入变量
- >使用 RegCreateKeyEx() 的 Windows 可执行文件不会提示输入 UAC 管理员权限并失败?
- 在 cin 失败时捕获无效输入