我想分别获得时间和日期,并将其放入数组中。我希望调用函数是int date(int Day,int Month,int Year)
,但这是不正确的。如何定义函数的年、月、日、时、分、秒参数来使用它们?
using namespace std;
int date() {
time_t currentTime;
struct tm *localTime;
time(¤tTime);
localTime = localtime(¤tTime);
int Day = localTime->tm_mday;
int Month = localTime->tm_mon + 1;
int Year = localTime->tm_year + 1900;
return (0);
}
int time() {
time_t currentTime;
struct tm *localTime;
time(¤tTime);
localTime = localtime(¤tTime);
int Hour = localTime->tm_hour;
int Min = localTime->tm_min;
int Sec = localTime->tm_sec;
return (0);
}
int main() {
unsigned int new_date=date();
char write[4];
memcpy(write,&new_date,4);
unsigned int new_time=time();
char wrt[4];
memcpy(wrt,&new_time,4);
}
必须声明函数通过引用传递参数:
// pass arguments by reference to change them in the function
int date(int &Day, int &Month, int&Year) {
time_t currentTime;
struct tm *localTime;
time(¤tTime);
localTime = localtime(¤tTime);
Day = localTime->tm_mday; // use the reference argument
Month = localTime->tm_mon + 1;
Year = localTime->tm_year + 1900;
return (0);
}
您可以在main()
中这样使用它:
int d,m,y;
date(d,m,y);
cout << d<<"/"<<m<<"/"<<y<<endl;
你当然可以对时间做同样的事情。