If you look at the description of ctime you will note:
This function returns a pointer to static data and is not thread-safe. In addition, it modifies the static tm object which may be shared with gmtime and localtime. POSIX marks this function obsolete and recommends strftime instead.
The behavior may be undefined for the values of time_t that result in the string longer than 25 characters (e.g. year 10000)
... that's a lot of things to worry about.
On the other hand, if you look at strftime:
size_t strftime( char* str, size_t count, const char* format, tm* time );
Return value
number of bytes written into the character array pointed to by str not including the terminating '\0' on success. If count was reached before the entire string could be stored, 0 is returned and the contents are undefined.
All the parameters are explicit, so that you fully control the possible data races, and there is no risk of overflowing the buffer provided as well.
This is the C-way though, and C++ introduces the <chrono>
in which a specific function std::put_time
can also be used to output time to a stream:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
int main() {
std::time_t const now_c = std::time();
std::cout << "One day ago, the time was "
<< std::put_time(std::localtime(&now_c), "%F %T") << '\n';
}
which is even better since you no longer have to worry about the possible buffer overflow.