loops - 输入无效的布尔值会导致 infin 错误。循环并阻止我输入更多信息
问题描述
在这里,我尝试制作一个基本的计算,只要用户想要,它就会添加整数。我遇到了一个问题,如果我为 bool 输入无效值,程序将无限运行循环。虽然如果用户没有输入无效值,这不是问题,但最好对代码进行万无一失。
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
// here i set up the code to create a calculator that will add
// as long as the user wants.
int Num1 ;
int Num2 ;
bool Permit = false;
cout<< "enter first number:"<<endl;
cin>> Num1;
cout<< "Do you wish to continue? 1 for yes 0 for no." <<endl;
cin>> Permit;
// here the loop should run only as long as the bool is true.
while (Permit)
{
cin>> Num2;
Num1 = Num2+Num1;
cout<< "Do you wish to continue? 1 for yes 0 for no." <<endl;
cin>> Permit;
}
cout <<Num1;
// however if i enter a value other than 0 or 1 , the whole
// loop runs infinitely , but doesnt allow me to enter any
// info.
// if i enter any alphabet instead of 0 or 1, the opposite
// happens the loop terminates immediately.
}
解决方案
推荐阅读
- python - 如何并行使用分页 API?
- jmeter - Jmeter 发送电子邮件以模拟 cjsm(安全)不使用 Base64 编码作为附件
- python - 为什么python与wireshark捕获的数据包之间存在很大差异
- css - PDFreactor text-decoration-color:如何对线进行着色?
- ionic4 - 从 google fit API 获取当前登录的用户信息(电子邮件或用户 ID)
- python - 没有名为站点 OSGEO4W 的模块
- cucumber-serenity - 如何将 serenity 测试结果导入 XRay 测试执行?
- java - 对 Java 和 Kotlin 友好的 Kotlin 侦听器
- ruby-on-rails - 如何有条件地在 Rails 中包含路由参数?
- google-apps-script - setValue 函数执行,但值未更新