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
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
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
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;
: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 ?
Could you pls tell what compiler do u use ?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
if (!cin || selection<0 || selection>5)
cout << "ERROR:Invalid Selection \n";