Link to home
Start Free TrialLog in
Avatar of sramkris
sramkris

asked on

How to trap an error

Hi,

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";
     else
     if (selection<0)
          cout << " You have entered a negative selection " << amount << "\n";
     else
     if  (selection>5)
          cout << " Invalid selection: " << amount << "\n";

Thanks

Avatar of lexxwern
lexxwern
Flag of Netherlands image

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";
Avatar of sramkris
sramkris

ASKER

Hi

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...

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

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

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 ?
ASKER CERTIFIED SOLUTION
Avatar of lexxwern
lexxwern
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial