简化if else用户输入验证

Simplifying if else user input validation

本文关键字:输入 验证 用户 else if 简化      更新时间:2023-10-16

这得到了我需要它做的工作,但我想知道是否有一种更容易/更有效的方式来完成同样的事情。用户输入两个数字,它们需要在0到50之间,如果不在要求的范围内,则结束进程

cout << "Enter the pixel coordinate (x, y): ";
cin >> usrInput1 >> userInput2;
if  (usrInput1 > 50)
{
    cout << "ERROR! 1" << endl;
    return 0;
}
else if (usrInput1 < 0)
{
    cout << "ERROR! 2" << endl;         
    return 0;
}
else if (usrInput2 > 50)
{
    cout << "ERROR! 3" << endl;
    return 0;
}
else if (usrInput2 < 0)
{
    cout << "ERROR! 4" << endl;
    return 0;
}
else
{
    cout << "Success" << endl;
    xvar = usrInput1 + usrInput2;
}

我想做一些类似

的事情
if(! 0 > userInput1 || userInput2 > 99)

但显然没有成功…

感谢您的帮助

cout << "Enter the pixel coordinate (x, y): ";
cin >> usrInput1 >> userInput2;
if  ( (usrInput1 > 50) || (usrInput1 < 0)  ||
      (usrInput2 > 50) || (usrInput2 < 0) )
{
    cout << "ERROR!" << endl;
    return 0;
}
cout << "Success" << endl;
xvar = usrInput1 + usrInput2;

实际上可以如果你真的想要的话,可以进一步合并:

if  ((std::max(usrInput1,usrInput2) > 50) 
   || std::min(usrInput1,usrInput2) < 0))
{ 
     ...
在这种情况下,我宁愿有一个辅助函数
bool isValid(int i) { return (i>=0) && (i<=50); }
// ...
if (isValid(usrInput1) && isValid(usrInput2))
    ...

编辑考虑检查输入操作- OP中缺少这一点:

<子>

if (!(cin >> usrInput1 >> userInput2))
{
     std::cerr << "input error" << std::endl;
}
if  ( (usrInput1 > 50) || (usrInput1 < 0)  ||
      (usrInput2 > 50) || (usrInput2 < 0) )
{
     std::cerr << "value out of range" << std::endl;
}

我想我会把它的大部分移动到一个函数:

bool check_range(int input, 
                  int lower, int upper, 
                  std::string const &too_low, std::string const &too_high) 
{
    if (input < lower) {
        std::cerr << too_low << "n";
        return false;
    }
    if (input > upper) {
        std::cerr << too_high << "n";
        return false;
    }
    return true;
}

那么你可以这样写:

if (check_range(usrInput1, 0, 50, "Error 1", "Error 2") &&
    check_range(usrInput2, 0, 50, "Error 3", "Error 4")
{
    // Both values are good
}

我应该补充一点,我对此并不完全满意。这个函数确实包含了两个我宁愿分开的职责(检查范围和在超出范围时报告错误)。