Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we limit user input in C++?

Tags:

c++

The problem is when the user input is = 9999999999 then the console is returning all the values. I want to limit this input by using simple else if statement if someone tried to put the value for a, b = 9999999999 then user must get the warning as I defined in my code. I can control it by using double instead of int but this is not a solution.

#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
        }
}
like image 263
Саша Avatar asked Dec 05 '22 08:12

Саша


1 Answers

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.

like image 200
ChrisMM Avatar answered Dec 28 '22 02:12

ChrisMM