Simplifying if else user input validation
This gets the job done for what I need it to do, but I am wondering if there is an easier/more efficient way of accomplishing the same thing. The user inputs two numbers and they need to be between 0 and 50, if it doesnt fall within the required range it ends the prog
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;
}
I was trying to do something like
if(! 0 > userInput1 || userInput2 > 99)
but obviously that didn't work out..
Thanks for any assistance
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;
You could actually combine it further if you really wanted:
if ((std::max(usrInput1,usrInput2) > 50)
|| std::min(usrInput1,usrInput2) < 0))
{
...
in which case I would rather have a helper function
bool isValid(int i) { return (i>=0) && (i<=50); }
// ...
if (isValid(usrInput1) && isValid(usrInput2))
...
Edit Consider checking the input operations - this was missing in the 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;
}
I think I'd move most of it into a function:
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;
}
Then you'd use this something like:
if (check_range(usrInput1, 0, 50, "Error 1", "Error 2") &&
check_range(usrInput2, 0, 50, "Error 3", "Error 4")
{
// Both values are good
}
I should add that I'm not entirely happy with this. The function does really embody two responsibilities that I'd rather were separate (checking the range and reporting the error if its out of range).
精彩评论