首页 > 解决方案 > 输入无效的布尔值会导致 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.
}

标签: loopsboolean

解决方案


推荐阅读