In: Computer Science
Language: C++
The program I have written below needs to allow the user to enter in their own date, however I currently can only get it to output a default date, 10/10/2018. After the user enters the date it needs to go through the exception checks to make sure it is a valid date. Afterword the user needs to be prompted to change their date.
Here is the code:
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstring>
#include <sstream>
#include <vector>
using namespace std;
class Date
{
private:
int month, day, year;
int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
string month_name[13] = { "","January","February","March","April","May","June","July","August","September","October","November","December" };
public:
Date(int m, int d, int y)
{
if (m < 1 || m>12)
{
throw "Invalid month";
}
if (d<1 || d>days[m])
{
throw "Invalid date";
}
if (y < 1950 || y>2020)
{
throw "Invalid year";
}
month = m;
day = d;
year = y;
}
void setMonth(int m)
{
if (m < 1 || m>12)
{
throw "Invalid month";
}
month = m;
}
void setYear(int y)
{
if (y < 1950 || y>2020)
{
throw "Invalid year";
}
year = y;
}
void setDate(int d)
{
if (d<1 || d>days[d])
{
throw "Invalid date";
}
day = d;
}
void toString()
{
cout << month_name[month] << " " << day << ", " << year << endl;
}
};
int main()
{
cout << "Please enter in the date in format mm,
dd, yyyy." << endl;
Date d(10, 10, 2018);
d.toString();
try
{
d.setDate(44);
}
catch (const char* msg)
{
cerr << msg << endl;
}
return 0;
}
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstring>
#include <sstream>
#include <vector>
using namespace std;
class Date
{
private:
int month, day, year;
int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
string month_name[13] = {
"","January","February","March","April","May","June","July","August","September","October","November","December"
};
public:
Date(int m, int d, int y)
{
if (m < 1 || m>12)
{
throw "Invalid month";
}
if (d<1 || d>days[m])
{
throw "Invalid date";
}
if (y < 1950 || y>2020)
{
throw "Invalid year";
}
month = m;
day = d;
year = y;
}
void setMonth(int m)
{
if (m < 1 || m>12)
{
throw "Invalid month";
}
month = m;
}
void setYear(int y)
{
if (y < 1950 || y>2020)
{
throw "Invalid year";
}
year = y;
}
void setDate(int d)
{
if (d<1 || d>days[d])
{
throw "Invalid date";
}
day = d;
}
void toString()
{
cout << month_name[month] << " " << day <<
", " << year << endl;
}
};
int main()
{
int D,m,y;
cout << "Please enter in the date in format mm, dd, yyyy."
<< endl;
cin>>D>>m>>y;
try
{
Date d(D,m,y);
d.toString();
}
catch (const char* msg)
{
cerr << msg << endl;
}
return 0;
}