Answer to Question #182265 in C++ for Mani

Question #182265

Write a program to accept name and age of a person from the user and ensure that the age

entered is >=18 and < 60. If the given age is in specified range then print "Valid age"

The program must exit gracefully after displaying the error message "Age is not valid" in case

the arguments passed are not proper (age is not in specified range). You should create a user

defined exception class for handling this error.


1
Expert's answer
2021-04-17T03:06:58-0400
#include <iostream>
#include <string>


using namespace std;




class AgeException : public exception{  
public:  
	const char * getMessage() const throw()  
	{  
		return "\nAge is not valid!\n";  
	}  
};  


int main()
{
	try {  
		string name;
		int age;
		cout<<"Enter the name of a person: ";
		getline(cin,name);
		cout<<"Enter the age of a person: ";
		cin>>age;
		if (age>=18 && age<60)  
		{  
			cout<<"\nValid age.\n";
		}  
		else  
		{  
			AgeException ageException;  
			throw ageException;  
		}  
	}  
	catch(AgeException& e)  
	{  
		cout << e.getMessage();  
	}


	system("pause");
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS