Hi, its an assignment i need to do. The while loop working on well when i input an integer but when a letter is being input, the while loop run for infinity. I had seen through the other thread but still cannot understand how to do. Please help...

while(choice!=1&&choice!=2&&choice!=3&&choice!=4)
    {cout<<"The request is invalid, please try again."<<endl;
    cout<<"Please enter your choice again"<<endl;
    cin>>choice;
    }

Recommended Answers

All 6 Replies

If there are less than 10 choices, take in the choice as a character rather than an integer. Check to make sure the character is between '1' and '9' (or '0' and '9' if you want a choice 0).

Alternatively, if a 2+ digit answer is required, take in the input as a string and check each character to see if it's a digit (using the functions in <cctype> if permitted or the approach above if it's not).

What is choice defined as?

the choice is declare as int...

then is normal to fail if you input a character...

define it as char or string

you made the condition as :

while(choice!=1&&choice!=2&&choice!=3&&choice!=4)

1 and 2 and 3 and 4 are intergers and the choice is character so you should make it as

while(choice!='1'&&choice!='2'&&choice!='3'&&choice!='4')

the choice is declare as int...

choice is character

I said choice should be a character. In the OP's code it is not.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.