LostITguy
LostITguy

Reputation: 37

How to set a range of int value in C++

If I have an int a; and I want to set a value for this int (cin >> a;) in a range 1 < a < 1000, what is the most effective way how to type it via code? Is there a better way then if(a <=1 || a >= 1000)? Since if I would have multiple of int which I wanted to be limited by their value, I don't want to type a condition for every single one.

Upvotes: 1

Views: 4435

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596517

Using the if is the best way to do what you are asking for. But, if you need to handle multiple ints, you should wrap the if inside of its own function that you can call whenever needed, eg:

int askForInt(int minValue, int maxValue)
{
    int value;
    do {
        cout << "Enter an integer (" << minValue << "-" << maxValue << "): ";
        if (cin >> value) {
            if (value >= minValue && value <= maxValue) break;
            cout << "Value out of range! Try again." << endl;
        }
        else {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Bad input! Try again." << endl;
       }
    }
    while (true);
    return value;
}

...

a = askForInt(1, 1000);

Upvotes: 1

qz-
qz-

Reputation: 1048

Checking the condition a <=1 || a >= 1000 is exactly what you'd do 👍 You will want to use a loop here, though, to re-ask for input if the input is not in the correct range.

Upvotes: 2

Related Questions