avr39-ripe

dateStruct

Oct 8th, 2019
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. struct Date
  4. {
  5.     enum err { OK, DAY, MONTH, YEAR};
  6.  
  7.     uint8_t day;
  8.     uint8_t month;
  9.     uint16_t year;
  10.    
  11.     void print();
  12.     int make(int8_t pDay, int8_t pMonth, int16_t pYear);
  13.     static void printError(int pErr);
  14.     static int isLeapYear(int16_t year);
  15.     static int daysInMonth(int8_t pMonth, int8_t pYear);
  16. };
  17.  
  18. void Date::print()
  19. {
  20.     std::cout << (int)day << '.' << (int)month << '.' << year << '\n';
  21. }
  22.  
  23. int Date::isLeapYear(int16_t pYear)
  24. {
  25.     return ((pYear % 4 == 0) and (pYear % 100 != 0 or pYear % 400 == 0));
  26. }
  27.  
  28. int Date::daysInMonth(int8_t pMonth, int8_t pYear)
  29. {
  30.     return 30 + ((pMonth < 8 and pMonth % 2 != 0) or (pMonth >= 8 and pMonth % 2 == 0)) + (pMonth == 2)*-2 + isLeapYear(pYear);
  31. }
  32.  
  33. int Date::make(int8_t pDay, int8_t pMonth, int16_t pYear)
  34. {
  35.     if (pDay < 1 or pDay > 31) { return Date::err::DAY; }
  36.     if (pMonth < 1 or pMonth > 12 ) { return Date::err::MONTH; }
  37.     if (pYear < 1) { return Date::err::YEAR; }
  38.     if (pDay > daysInMonth(pMonth,pYear)) { return Date::err::DAY; }
  39.  
  40.     day = pDay;
  41.     month = pMonth;
  42.     year = pYear;
  43.  
  44.     return Date::err::OK;
  45. }
  46.  
  47. void Date::printError(int pErr)
  48. {
  49.     if (pErr == Date::err::DAY) { std::cout << "Bad day!\n"; }
  50.     if (pErr == Date::err::MONTH) { std::cout << "Bad month!\n"; }
  51.     if (pErr == Date::err::YEAR) { std::cout << "Bad year!\n"; }
  52. }
  53.  
  54. int main()
  55. {
  56.     std::cout << "Size of Date struct is: " << sizeof(Date) << '\n'; //No additional bytef for err enum!!! :)
  57.  
  58.     Date d1{};
  59.     if (auto dateErr = d1.make(29, 2, 2004) > Date::err::OK)
  60.     {
  61.         Date::printError(dateErr);
  62.     };
  63.     d1.print();
  64.    
  65.     Date d2{};
  66.     if (auto dateErr = d1.make(29, 2, 2005) > Date::err::OK)
  67.     {
  68.         Date::printError(dateErr);
  69.     };
  70.     d2.print();
  71.  
  72.     int testMonth = 2;
  73.     int testYear = 2004;
  74.     std::cout << "Is " << testYear << " leap year? " << Date::isLeapYear(2004) << '\n'; //Call static member function without instance
  75.     std::cout << "How much days are in " << testMonth << " month of " << testYear << " year? " <<  Date::daysInMonth(2,2004) << '\n'; //Call static member function without instance
  76. }
Advertisement
Add Comment
Please, Sign In to add comment