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

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?

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 3 Years Ago by nullptr

This article has been dead for over six months. Start a new discussion instead.