**Why is it that when i use ctime to capture the time I am getting this error:

time_t
now = time(0);// convert now to string form
char* dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;

error C4996: 'ctime': This function or variable may be unsafe. Consider using ctime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
**

Edited 3 Years Ago by VBOI

Because your compiler thinks using ctime is such a bad, bad idea that it's not going to let you do it unless you specifially tell it to let you.

char      TimeBuffer[26] = {};
time_t    RawTime        = 0;
time(&RawTime);
ctime_s(TimeBuffer, 26*sizeof(char), &RawTime);

Because your compiler thinks using ctime is such a bad, bad idea that it's not going to let you do it unless you specifially tell it to let you.

Actually, that's just a warning. He (wisely) has warnings set to fire as errors, but in the case of 4996, it's usually spurious. We can debate the merits of the warning in this case, but without more information about the program it's not conclusive.

A better solution, in my opinion, than ctime_s (which isn't widely supported or standard in C++) is strftime.

But why when i try this your solution^^^^, i still keep getting warning:

error C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

  #include <stdio.h>      /* puts */
   #include <time.h>       /* time_t, struct tm, time, localtime, strftime */

   int main ()
   {
   time_t rawtime;
   struct tm * timeinfo;
   char buffer [80];

   time (&rawtime);
   timeinfo = localtime (&rawtime);

   strftime (buffer,80,"Now it's %I:%M%p.",timeinfo);
   puts (buffer);

   return 0;
   }

Actually, that's just a warning.

I understand your point; I nonetheless maintain that this is an error, because it says "error" on it and it stops the compilation :) It would indeed be a warning in other circumstances, including different compiler settings.

Edited 3 Years Ago by Moschops

But why when i try this your solution^^^^, i still keep getting warning:

I always disable that warning, and even though I'm paranoid about disabling warnings, don't hesitate to recommend the practice in this case. 4996 is just Microsoft forcing you to use their non-standard library.

Edited 3 Years Ago by deceptikon

This article has been dead for over six months. Start a new discussion instead.