首页 > 解决方案 > 我们可以限制 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
        }
}

标签: c++

解决方案


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.


推荐阅读