检查整数输入时,输入验证循环从char输入陷入无限循环

时间:2019-06-07 10:25:50

标签: c++ validation input

我正在尝试使用while循环来测试用户是否输入了有效的1到3整数选择。如果我输入一个整数,则它会通过拒绝超出指定范围的任何内容来正常工作。如果输入字母,则会陷入无限循环。

我非常确定这与字母有关,并且是ASCII值,所以我尝试将输入的类型强制转换为优惠券为int,但这并没有改变问题。

int main()
{
    const float adult_haircut = 15.50, child_haircut = 10.50; // haircut 
         prices without discount
    int coupon; // the coupon the user has

    cout << "Please enter the number corresponding to the coupon color your 
         have. If you have no coupon then enter 3 for none. \n";
    cout << "1 - Green \n";
    cout << "2 - Blue \n";
    cout << "3 - None \n";
    cin >> coupon; // reads coupon color and stores it in the variable

// while loop tests for valid data input
    while (coupon < 1 || coupon > 3)
    {
        cout << "Not a valid choice, please enter the number corresponding to 
           the coupon color your have. If you have no coupon then enter 3 for 
           none. \n";
        cout << "1 - Green \n";
        cout << "2 - Blue \n";
        cout << "3 - None \n";
        cin >> coupon; // reads coupon color and stores it in the variable
    }

我希望代码拒绝任何不在指定范围内的字母或数字,并重复选择。

0 个答案:

没有答案