Ext*_*t23 1 c++ validation input
这可以完成我需要它做的工作,但我想知道是否有更简单/更有效的方法来完成同样的事情.用户输入两个数字,它们需要介于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;
}
Run Code Online (Sandbox Code Playgroud)
我试图做类似的事情
if(! 0 > userInput1 || userInput2 > 99)
Run Code Online (Sandbox Code Playgroud)
但显然没有成功..
谢谢你的帮助
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;
Run Code Online (Sandbox Code Playgroud)
如果你真的想要,你可以将它进一步组合:
if ((std::max(usrInput1,usrInput2) > 50)
|| std::min(usrInput1,usrInput2) < 0))
{
...
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我宁愿有一个辅助函数
bool isValid(int i) { return (i>=0) && (i<=50); }
// ...
if (isValid(usrInput1) && isValid(usrInput2))
...
Run Code Online (Sandbox Code Playgroud)
编辑考虑检查输入操作 - 这在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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1842 次 |
最近记录: |