Hi, I'm writing a code to print weekday (ie: mon, tue, wed, thurs, fri, sat, sun) when user enter day/month/year.
However, I do not know why this code doesn't work right.
I didn't get any error.
It actually works, but it just printed "Monday" for whatever date I putted in.
Could you please help me. I think I nearly get to the end. :)
here is the code:
date.h
#ifndef DATE_H
#define DATE_H
class Date {
public:
Date (int day, int month, int year);
Date();
Date(const Date& orig);
virtual ~Date();
int getDay ();
void setDay (int day);
int getMonth ();
void setMonth (int month);
int getYear ();
void setYear (int year);
bool isLeapYear (int year);
int daysInMonth (int day, int month, int year);
void advance ();
bool precedes (Date date);
private:
int day_;
int month_;
int year_;
};
#endif /* DATE_H */
date.cpp
#include "Date.h"
Date::Date(int day, int month, int year) {
this->day_ = day;
this->month_ = month;
this->year_ = year;
}
int Date::getDay(){
return this->day_;
}
void Date::setDay(int day){
this->day_ = day;
}
int Date::getMonth(){
return this->month_;
}
void Date::setMonth(int month){
this->month_ = month;
}
int Date::getYear() {
return this->year_;
}
void Date::setYear(int year){
this->year_ = year;
}
bool Date::isLeapYear(int year) {
if ((year % 400 == 0 && year % 100 != 0) || (year % 4 == 0))
return false;
else return true;
}
Date::daysInMonth(int day, int month, int year){
switch (month){
case 9:
case 4:
case 6:
case 11:
return 30;
default:
return 31;
case 2:
return this-> isLeapYear(year_) ? 29 : 28;
}
}
void Date::advance() {
this -> day_;
if (this->day_ > this->daysInMonth(day_, month_, year_)) {
this->day_ = 1;
this->month_++;
}
if (this->month_ > 12) {
this->month_ = 1;
this->year_++;
}
}
bool Date::precedes(Date date){
return this->year_ < date.year_
|| this->year_ == date.year_ && this->month_ < date.month_
|| this->year_ == date.year_ && this->month_ == date.month_ && this->day_ < date.day_;
}
Date::Date(const Date& orig) {
}
Date::~Date() {
}
main.cpp
#include <cstdlib>
#include <iostream>
#include "Date.h"
using namespace std;
/*
*
*/
int main() {
int day, month, year;
cout << "What date (d m y)? ";
cin >> day, month, year;
const string days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
Date trial = Date (01,01,1900);
Date d2 = Date (01,01,1899);
int weekday = 1;
if (d2.precedes (trial)){
cout << "Mysteryday" << endl;
} else {
while (trial.precedes(d2)) {
trial.advance();
weekday = (weekday+1) % 7;
}
cout << "That was a " + days [weekday];
}
// return 0;
}