c++ - 我们可以限制 C++ 中的用户输入吗?
问题描述
问题是当用户输入 = 9999999999 时,控制台将返回所有值。我想通过使用简单的else if语句来限制这个输入,如果有人试图输入 a, b = 9999999999 的值,那么用户必须得到我在代码中定义的警告。我可以通过使用 double 而不是 int 来控制它,但这不是解决方案。
#include <iostream>
using namespace std;
main()
{
int a, b, c, d;
cout << "Enter Value for A: ";
cin >> a;
cout << "Enter Value for B: ";
cin >> b;
if (a > b)
{
cout << "A is Greater than B " << endl; //This will be printed only if the statement is True
}
else if ( a < b )
{
cout << "A is Less than B " << endl; //This will be printed if the statement is False
}
else if ( a, b > 999999999 )
{
cout << " The Value is filtered by autobot !not allowed " << endl; //This will be printed if the statement is going against the rules
}
else
{
cout << "Values are not given or Unknown " << endl; //This will be printed if the both statements are unknown
}
cout << "Enter Value for C: ";
cin >> c;
cout << "Enter Value for D: ";
cin >> d;
if (c < d)
{
cout << c << " < " << d << endl; //This will be printed if the statement is True
}
else if ( c > d )
{
cout << "C is Greater than D " << endl; //This will be printed if the statement is False
}
else
{
cout << c << " unknown " << d << endl; //This will be printed if the statement is Unknown
}
}
解决方案
Here's an example function which ensures valid input. I've made it take in a min and max value too, but you don't necessarily need them, since 999999999 is going to be out of the range of int
anyway, which causes cin
to fail. It will wait for valid input though.
int getNum( int min, int max ) {
int val;
while ( !( cin >> val ) || val < min || val > max ) {
if ( !cin ) {
cin.clear();
cin.ignore( 1000, '\n' );
}
cout << "You entered an invalid number\n";
}
return val;
}
int main() {
int a = getNum( 0, 12321 );
}
EDIT: Well, now you just modified your question to have using simple else if statement, changing the answers. The answer then, is simply no. Since cin
would fail, you can't realistically do a check. Also, it would never be true since 999999999
is greater than INT_MAX
on any implementation I can think of.
推荐阅读
- nuxeo - 覆盖 Nuxeo 中的默认图片转换
- nginx - Nginx - “systemctl status nginx”上的错误
- primefaces - 如何使用 Java 更改 Primefaces 7.0 ChartJS Linechart 的 Y 轴?
- php - 如何在 mysql json Array 数据中编写 SELECT 查询
- reactjs - 使用 react-picky 选择菜单时出现问题
- laravel - Laravel 控制器/商店
- amazon-web-services - 如何使用 Cloudformation 将代码从 aws s3 存储桶安全地提取到 Codecommit 存储库?
- python - 为什么我的元音删除功能不起作用?(Python 2.7)
- jhipster - Jhipster 重置电子邮件
- arrays - 我们可以降低将数组中的每个用户相互比较的复杂性吗?