C++ 之Date類實現輸入時間和加1天時間
阿新 • • 發佈:2018-12-16
定義日期類Date。要求:
(1)可以設定日期;
(2)日期加一天操作;
(3)輸出函式,輸出格式為“XXXX-XX-XX”;
(4)編寫主函式,定義物件,完成相應功能。
程式的參考的輸入(“Input Date:”為提示文字):
Input Date:2016 2 28
程式的輸出:
2016-2-28
2016-2-2
本程式是由 QTCreator在linux作業系統下完成的,僅供參考
Date類的標頭檔案
#ifndef CDATE_H #define CDATE_H class CDate { private: int year; int month; int day; int YearNL[12]= {31,28,31,30,31,30,31,31,30,31,30,31}; int YearL[12]={31,29,31,30,31,30,31,31,30,31,30,31}; char WhileFlag = 'n'; //set a WhileFlag to deal error input char flagleap='n'; public: //void SetDate(int year, int month, int day); void SetDate(); void AddDate(); void GetDate(); char LeapYear(); }; #endif // CDATE_H
Date類的實現
#include "cdate.h" #include <iostream> using namespace std; char CDate::LeapYear() { if(( 0 == year%400 ) || ( 0 == year %4&& 0!= year%100 )) { cout<<year<<" is a leap year "<<endl<<endl; //if the year is a leap year then check it with YearL[] if(day > YearL[month-1]) { cout <<"invalid value ! input again "<<endl<<endl; return WhileFlag = 'n'; } //return the WhileFlag else { return WhileFlag ='y',flagleap='y'; } } //if the year is not a leap year then check it with YearNL[] else { if(day > YearNL[month-1]) { cout <<"invalid value ! input again "<<endl<<endl; return WhileFlag = 'n'; } //return the WhileFlag else { return WhileFlag ='y'; } } } void CDate::SetDate() { while(WhileFlag == 'n') { cout <<"Please input [ year month day ]:"; cin >>year>>month>>day; this->year = year; this->month = month; this->day = day; cout<<endl<<"Yourinput:"<<year<<"-"<<month<<"-"<<day<<endl<<endl; LeapYear(); } } //add one day void CDate ::AddDate() { //if user input a leap year and the day is 29 ,the tomorrow day will be change if(( 'y' == flagleap ) && ( day == YearL[month-1] )) { day = 1; cout << "Tomorrow is:"<<year<<"-"<<month+1<<"-"<<day<<endl; } //else output directly else if(day == YearNL[month-1]) //if the day is the end of month,then set the day=1 { day = 1; cout << "Tomorrow is:"<<year<<"-"<<month+1<<"-"<<day<<endl<<endl; } else //else it can add directly { cout << "Tomorrow is:"<<year<<"-"<<month<<"-"<<day+1<<endl<<endl; } } //get the date void CDate::GetDate() { SetDate(); //call the Set() to set date cout<<"The date is:"<<year<<"-"<<month<<"-"<<day<<endl; AddDate(); }
Main函式
#include <iostream>
#include "cdate.h"
using namespace std;
int main()
{
CDate Date1; //creat a object Date1
Date1.GetDate(); //call the Get method to obtain date
return 0;
}
執行結果:
為了區別瑞年和平年,我輸入了1880 的2月 29日;如圖顯示
輸入的2018年的10月16日: