How to trap an error


I have declared a variable as integer and i make some calculations based on the user input..I have taken care of negative numbers but how to trap if the user enters anything other than a number...

here is the sample code which i have used..

cout << "Choose a option of your choice: \n";
cin >> selection;

     if (!cin)
          cerr << "Invalid selection \n";
     if (selection<0)
          cout << " You have entered a negative selection " << amount << "\n";
     if  (selection>5)
          cout << " Invalid selection: " << amount << "\n";


Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

what you're doing is okay but i just sweetened it a bit with some modifications.

if (!cin || selection<0 || selection>5)
   cout << "ERROR:Invalid Selection \n";
sramkrisAuthor Commented:

This still does not work...If i enter a alphabet or any other key apart from a number it just scrolls or rather hangs...IT does not solve the problem...Is there any way i can force the user to only use numbers...

If Ur using Getchar() U can verify the input by checking the char between 48 - 57

char ch= Getchar()
if( ch<48 && ch > 57 )
   GoTo gch;

Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

The only way you can check for invalid inputs is by taking char input and converting it to int if it is valid.
It works very well in my compiler.
Could you pls tell what compiler do u use ?
char ch= Getchar()
if( !(ch<48 && ch > 57) )

         cout << " You have entered a negative selection " << amount << "\n";

this should do it or you.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.