0
void Project1(){
       unsigned short int x;
       bool flag = false;
       cout << "Enter an interger, I will reversed i.e. 301 --> 103" << endl;
       cin >> x;
       if ((x > 0) && (x <= 65535) ){ 
                flag == true;
                cout << reverse_num(x);
                cout << endl;
        }
        else {
                cout << "No conversion possible." << endl;
        }
}

I having trouble when i enter a number out of the range of unsigned short int

3
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by nullptr
1

You will have trouble when you enter anything outside the range of the target variable's type. It's usually wise to use a type that holds more range or precision that what you expect input to be, if you don't have strict control of the input.

Is there a particular reason to limit yourself to short int? If that's to be the range, why not use an int for input, and test that the value is within the range you intend to process?

1

You could also handle invalid input like this:

    unsigned short int x;
    bool flag = false;
    cout << "Enter an integer that I will reverse i.e. 301 --> 103" << endl;

    while (!flag)
    {
        cin >> x;
        if (cin.fail() )
        {
            // clear error flags and flush input
            cin.clear();
            cin.ignore(90, '\n');
            cout << "Invalid input, enter another integer" << endl;
            continue;
        }

        flag = true;
    }
    cout << reverse_num(x);
    cout << endl;

Edited by nullptr

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.