In: Computer Science
(In c++ language)
1A) Write a void function GetYear that prompts for and inputs the year the operator was born (type int) from standard input. The function returns the user’s birth year through the parameter list (use pass by reference) unless the user enters an invalid year, in which case a BadYear exception is thrown. To test for a bad year, think about the range of acceptable years. It must be 4 digits (i.e. 1982) and it cannot be greater than the current year (the user obviously cannot be born in a calendar year that has yet to happen!).
1B) Write a try-catch statement that calls the GetYear function defined above. If a BadYear exception is thrown, print an error message and rethrow the exception to a caller; otherwise, execution should just continue as normal.
1.A) The program is given below. The comments are provided for the better understanding of the logic.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void GetYear(int &year)
{
//Declare a variable to store the year for temp purpose
int tempYear;
//Get the year from the user
cout << "Enter the Year of birth: ";
cin >> tempYear;
//Validate the year
int length = to_string(tempYear).length();
//validate for year length = 4
if (length != 4)
//If the length is not equal to 4, throw an error back.
throw "BadYear";
else
{
//Validate if the entered year is greater than the curent year
//The below block will get the current year in the variable currentYear
char tempTimeCharVar[50];
time_t tempTimeVar = time(NULL);
errno_t e = ctime_s(tempTimeCharVar, 50, &tempTimeVar);
int timeVarLength = strlen(tempTimeCharVar);
string tempDateString(tempTimeCharVar);
int currentYear = stoi(tempDateString.substr(timeVarLength-5));
//Check if the entered year is greater than the current year.
if(tempYear > currentYear)
//If so, throw error.
throw "BadYear";
}
//If this code is reached the year entered is fine and that will be assigned to the refernce variable year.
//The variable year will be accessible in the calling method with the modified value.
year = tempYear;
}
int main()
{
int year;
//Call the GetYear function
GetYear(year);
//Print the year returned as reference from the function.
cout << "The year entered is : " << year << endl;
}
The screenshots of the code and output are provided below.
1.B) The try catch statement can be used as follows.
int main()
{
int year;
try
{
//Call the GetYear function
GetYear(year);
//Print the year returned as reference from the function.
cout << "The year entered is : " << year << endl;
}
catch(exception e)
{
//Display the error message and rethrow
cout << e.what() << endl;
throw e.what();
}
}