简化 if else 用户输入验证
这可以完成我需要做的工作,但我想知道是否有一种更简单/更有效的方法来完成同样的事情。用户输入两个数字,它们需要在 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)
,但显然没有成功。
感谢您的帮助
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你真的想要的话,你实际上可以进一步组合它:
在这种情况下,我宁愿有一个辅助函数
编辑考虑检查输入操作 - 这在OP中缺失:
<子>
You could actually combine it further if you really wanted:
in which case I would rather have a helper function
Edit Consider checking the input operations - this was missing in the OP:
我想我会把它的大部分移到一个函数中:
然后你会使用这样的东西:
我应该补充一点,我对此并不完全满意。该函数确实体现了我宁愿分开的两个职责(检查范围并在超出范围时报告错误)。
I think I'd move most of it into a function:
Then you'd use this something like:
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).