直接设置结构 tm 属性的值不起作用

Directly setting values of struct tm's attributes not working

本文关键字:不起作用 属性 tm 设置 结构      更新时间:2023-10-16

为什么asctime(ptr)什么也没有返回?结构体的所有变量都有值。有人能解释一下为什么会这样吗?

我也尝试使用strftime,但结果是相同的。

#include <iostream>
#include <ctime>
#include <new>
//#include <cstdio>
using namespace std;
int main(int argc,char *argv[])
{
    struct tm *ptr=new struct tm;
    //char buf[50];
    ptr->tm_hour=0;
    ptr->tm_mon=0;
    ptr->tm_year=0;
    ptr->tm_mday=0;
    ptr->tm_sec=0;
    ptr->tm_yday=0;
    ptr->tm_isdst=0;
    ptr->tm_min=0;
    ptr->tm_wday=0;
    cout << asctime(ptr);
    //strftime(buf,sizeof(char)*50,"%D",ptr);
    //printf("%s",buf);
    return 0;
}

下面的程序可以工作。用1去掉0就可以了。

    struct tm *ptr = new struct tm();
char buf[50];
ptr->tm_hour = 1;
ptr->tm_mon = 1;
ptr->tm_year = 1;
ptr->tm_mday = 1;
ptr->tm_sec = 1;
ptr->tm_yday = 1;
ptr->tm_isdst = 1;
ptr->tm_min = 1;
ptr->tm_wday = 1;
cout << asctime(ptr)

 ptr->tm_hour = 0;
ptr->tm_mon = 0;
ptr->tm_year = 0;
ptr->tm_mday = 1;
ptr->tm_sec = 0;
ptr->tm_yday = 0;
ptr->tm_isdst = 0;
ptr->tm_min = 0;
ptr->tm_wday = 0;
cout << asctime(ptr);

如果struct tm的任何成员超出其正常范围,则asctime的行为是未定义的。

特别是当日历日小于0时,该行为是未定义的(某些实现将tm_mday==0处理为前一个月的最后一天)。

请查看http://en.cppreference.com/w/cpp/chrono/c/asctime和http://en.cppreference.com/w/cpp/chrono/c/tm了解更多详细信息。