**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.
**

Recommended Answers

All 12 Replies

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.

any other way to capture the time in c++?

The error message did offer you an alternative.

how would you use ctime_s ?

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

how to i ouput that to the console?

You can output an array of char using the popular cout mechanism.

cout << time << endl; ?

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.