I have a program where I have a residential class derived from property base class. Residential has a private member as int bedrooms. I want to do error handling on this to check if value entered is an alphabet or valid number, I tried isdigit and atoi but it doesn't work. Any suggestions for this? here is a snippet of the code:
class Residential:public Building
{
private:
int bedroom;
public:
Home ()
{
bedroom=0;
}
void get()
{
int rooms;
cout<<"\n Enter the number of bedrooms (must be less than 10):";
cin>>rooms;
if(isalpha(rooms)) rooms=0;
while((rooms < 1)||(rooms > 14)){ //no. bedrooms condition
rooms =0;
cout<<"\n Invalid Entry. Try again:";
cin>>rooms;
if(isalpha(rooms)) rooms=0;
}
bedroom = rooms;
}//end get
};// end Residential
this code is not working properly if i enter a character, but works for any integer value. How can I prevent character entry also (use exception handling?).
Please use [code][/code] tags.
To see how to validate user input from cin see http://www.cplusplus.com/forum/articles/6046/
You can then throw exceptions if you get wrong input but you don't really need to
the constructor must be Residential not Home right? as input, you could also try control it through checking if it is valid as Bazzy said or make your own type of input that will ignore characters that aren't valid (like conio.h -> kbhit() & getch())