Answer to Question #212224 in C++ for Hemambar

Question #212224

Create a class Date whose object can store a day, month and year. Include the necessary

constructors to initialize the objects and function to display the date in ‘dd/mm/yyyy’ format.

Define a non-member function findAge(Date dob, Date today) which should return the calculated

age from the input dates ‘dob’ and ‘today’. Set this function as friend to Date class. Write a main

function to read the today’s date and date of birth of a person from the user and display the age

of that person by calling the proper function.


1
Expert's answer
2021-07-04T17:12:43-0400
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <ctime>//get current date time
#include <string.h>
using namespace std;
//Function string to integer
int toInt(string num)
{
	int ans = 0;
	for (int i = 0; i < num.length(); i++)
		ans = ans * 10 + (num[i] - '0');
	return ans;
	//for example "123"->0*10+1=1  ->1*10+2=12->12*10+3=123
	//return 123
}
//Implementation class Date
class Date
{
private:
	int d;//Day
	int m;//Month
	int y;//Year
public:
	//Default constructor (setting curent date using tm structure)
	Date()
	{
		time_t cur = time(0);//Second 1900 ...to curent year
		tm now = *localtime(&cur);
		this->d = now.tm_mday;//Set curent day
		this->m = now.tm_mon+1;//set curent month+1 [0..6]+1
		this->y = now.tm_year+1900;//set curent year+1900
	}
	//Parameterized Constructor
	Date(int _d, int _m, int _y)
	{
		this->d = _d;
		this->m = _m;
		this->y = _y;
	}
	//Constructor parse string date format dd/mm/yyyy
	Date(string dt)//Parse format string dd/mm/yyyy
	{
		int i = 0;
		string cur = "";
		//Read to /-symbol (day)
		while ((i < dt.length()) && dt[i] != '/')
		{
			cur += dt[i];
			i++;
		}
		i++;
		this->d = toInt(cur);
		cur = "";
		//read to / symbol (month)
		while ((i<dt.length())&&dt[i] != '/')
		{
			cur += dt[i];
			i++;
		}
		i++;
		this->m = toInt(cur);
		cur = "";
		while (i < dt.length())
		{
			cur += dt[i];
			i++;
		}
		this->y = toInt(cur);
	}
	//function format out date dd/mm/yyyy
	void printDate()
	{
		cout << this->d / 10 << this->d % 10 << "/" << m / 10 << m % 10 << "/" << this->y << endl;
	}
	//Friend funtion finAge(Date dob,Date today) which return age
	friend int findAge(Date dob, Date today);
	//Destructor
	~Date()
	{


	}
};
int findAge(Date dob, Date today)
{
	return today.y - dob.y;
}
int main()
{
	cout << "Please enter Date of birth (format dd/mm//yyyy): ";
	string db;
	cin >> db;
	Date d(db);
	Date cur;//Automaticaly curent date
	cout << "Current Date: ";
	cur.printDate();
	cout << "Age: "<<findAge(d, cur) << endl;


	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