简化if else用户输入验证
Simplifying if else user input validation
这得到了我需要它做的工作,但我想知道是否有一种更容易/更有效的方式来完成同样的事情。用户输入两个数字,它们需要在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
}
我应该补充一点,我对此并不完全满意。这个函数确实包含了两个我宁愿分开的职责(检查范围和在超出范围时报告错误)。
相关文章:
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- cin 的十进制输入验证?
- 输入验证以筛选出字符、字符串和一系列整数
- 输入验证将数字放入向量中
- 在C++中使用字符数组进行输入验证
- 在C++中使用字符数组进行用户输入验证
- C++ 中字符数组的输入验证
- 检查节点的输入验证的整数
- 如何让我的程序在输入验证的基础上读取素数
- C++ 用户输入验证无法正常工作
- 程序终止,而不是继续整数输入验证循环
- 使用REGEX进行电子邮件输入验证C
- C++:输入验证器函数
- 将用户输入验证为整数:用户必须两次输入输入
- C 输入验证
- C :对输入验证函数进行编程的性能影响可以对其进行编程,而每次都可以将其编程
- 使用模板函数进行通用输入验证
- 为什么用于输入验证的 while 循环要么完全跳过循环,要么不考虑错误的输入
- 仅 C++ 字母和空格输入验证