読者です 読者をやめる 読者になる 読者になる

個人的自由ノート

ふと自分が気になった事を書いてます

C++で問題を解く

#include <iostream>
#include <sstream>
#include <ctime>
#include <string>

class Date {
  int year;
  int month;
  int day;
public:
  Date();
  Date(const int& y, const int& m, const int& d);

  int getYear() const { return this->year; }
  int getMonth() const { return this->month; }
  int getDay() const { return this->day; }

  Date preceding_day() const;
  std::string to_string() const;
};

std::ostream& operator<<(std::ostream& s, const Date& x);
std::istream& operator>>(std::istream& s, Date& x);

using namespace std;

Date::Date(){
  time_t current = time(NULL);
  struct tm *local = localtime(&current);

  this->year = local->tm_year + 1900;
  this->month = local->tm_mon + 1;
  this->day = local->tm_mday;
}

Date::Date(const int& y, const int& m, const int& d){
  this->year = y;
  this->month = m;
  this->day = d;
}

Date Date::preceding_day() const {
  Date temp = *this;
  int day_max[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

  if(temp.day > 1)
    temp.day--;
  else {
    if(temp.month > 1)
      temp.month--;
    else {
      temp.year--;
      temp.month = 12;
    }
    temp.day = day_max[temp.month - 1];
  }

  return temp;
}

string Date::to_string() const {
  ostringstream s;
  s << this->year << "年" << this->month << "月" << this->day << "日";
  return s.str();
}

ostream& operator<<(ostream& s, const Date& x){
  return s << x.to_string();
}

istream& operator>>(istream& s, Date& x){
  int yy, mm, dd;
  char ch;

  s >> yy >> ch >> mm >> ch >> dd;
  x = Date(yy, mm, dd);
  return s;
}

int main(void){
  Date xday;
  const Date birthday(1963, 11, 18);
  Date day[3];

  cout << "xdayは : "; cin >> xday;
  cout << "その日の前日は" << xday.preceding_day() << "です。" << endl;
  cout << "birthday = " << birthday << endl;

  for(int i = 0; i < 3; i++)
    cout << "day[" << i << "]の文字列表現 : \"" << day[i].to_string() << "\"\n";
}