检查输入是否为特定类型并在特定范围内

Checking if an input is a particular type and in a particular range

本文关键字:范围内 类型 输入 检查 是否      更新时间:2023-10-16

我正在尝试测试用户输入的输入,以便我的程序不能中断。我正在使用的行是:

while (check != 0){
    cout << "Please enter a number 1 - 4 (area of: circle, rectangle, triangle or quit)" << endl;
    cin >> response;

    if ((isdigit(response)) && ((response >= 1) && (response <= 4))){
        check = 0;
    }
    else{
        cout << "You did not enter a valid digit (1 - 4)" << endl;
        check = 1;
    }
} // End of while loop

我要做的是检查输入是否是一个数字(具体是整数),并且在1和4的范围内。由于某种原因,我输入的每个值都被认为使用此方法无效。为了得到我想要的结果,我应该改变或做些什么呢?(这样它就会检查输入是否是一个整数,以及这个整数是否在1到4之间(包括1和4))。

假设response的类型为char,则需要使用字符常量'1''4',而不是整数常量14

if ((isdigit(response)) && ((response >= '1') && (response <= '4'))){

if (response >= '1' && response <= '4')就是你所需要的。如果输入的字符在正确的范围内,则必须是数字,因此不需要对isdigit进行测试。多余的圆括号也不是。