Directly setting values of struct tm's attributes not working

1.1k views Asked by At

Why does asctime(ptr) return nothing? All the variables of the struct have values. Can someone explain why does this happen?

I also tried using strftime but the result was the same.

#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;
}
2

There are 2 answers

3
Spanky On BEST ANSWER

The below program works. Remove zero with 1 and it will work.

    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)

This also works:

 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);
0
manlio On

The behavior of asctime is undefined if any member of struct tm is outside its normal range.

Especially the behavior is undefined if the calendar day is less than 0 (some implementations handle tm_mday==0 as meaning the last day of the preceding month).

Take a look at http://en.cppreference.com/w/cpp/chrono/c/asctime and http://en.cppreference.com/w/cpp/chrono/c/tm for further details.