-2

I am using netbean ide for c++ study I would like to force the user to pick only number between 1 to 3

int displayMenu()
{
    while(true)
    {  
        cout<<"Please choose one of following options"<<endl;
        cout<<"1. deposit"<<endl;
        cout<<"2. withdraw"<<endl;
        cout<<"3. exit"<<endl;
        int input;
        cin >>input;

        if(input>=1 && input<=3 && cin)
        {
            return input;
            break;
        }
        else
        {
            cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
        }
    }
}

It works fine if the input is int number If input is less then 1 or greater than 3, this function re-ask user to input number btw 1 and 3.

However, if the input is character such as 'f', it does an infinite loop. This function know that 'f' is wrong input..

I did my own research in the Internet. !cin and cin.fail() do not work.

Can you help me?

tux3
  • 7,171
  • 6
  • 39
  • 51
nrdream
  • 11

2 Answers2

0

When you try to read an integer but pass something else, the reading fails and the stream becomes invalid. Whatever caused the error remains in the stream. This leads to infinite loop.

To fix that, clear the error flags and ignore the rest of the line in your else clause:

    else
    {
        cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
        cin.clear(); // remove error flags
        // skip until the end of the line
        // #include <limits> for std::numeric_limits
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
Maksim Solovjov
  • 3,147
  • 18
  • 28
0

You can modify it like this:

int displayMenu()
{
    while(true)
    {  
        cout<<"Please choose one of following options"<<endl;
        cout<<"1. deposit"<<endl;
        cout<<"2. withdraw"<<endl;
        cout<<"3. exit"<<endl;
        char input = cin.get();  //read a character

        cin.ignore(numeric_limits<streamsize>::max(), '\n');  //skip the rest of characters in cin buffer so that even if a user puts "123" only the first one is taken into account

        if(input>='1' && input<='3' && cin)  //check whether this is '1', '2' or '3'
        {
            return input;
            break;
        }
        else
        {
            cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
        }
    }
}
psliwa
  • 1,094
  • 5
  • 9