gpt4 book ai didi

c - 最初和 sleep 结束时在 C 中打印时间

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:53 24 4
gpt4 key购买 nike

我正在尝试打印两次日期:

char *init_time = getTime();
// Do something and sleep 5 seconds
char *end = getTime();
printf("train 2 started at %s and arrived at %s\n", init_time, end);

获取时间:

char* getTime(){
time_t result;
result = time(NULL);
return asctime(localtime(&result));
}

为什么打印的结果一样?

最佳答案

来自 asctime 手册页:

The asctime() function converts the broken-down time value tm intoa null-terminated string with the same format as ctime(). The returnvalue points to a statically allocated string which might beoverwritten by subsequent calls to any of the date and time functions.The asctime_r() function does the same, but stores the string in auser-supplied buffer which should have room for at least 26 bytes.

换句话说,您对 asctime 的第二次调用将其结果存储在存储第一次调用结果的同一缓冲区中。

如果您想保留结果以备后用,请将结果复制到某处,或者在获得结果后立即打印,或者使用asctime_r

关于c - 最初和 sleep 结束时在 C 中打印时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37422556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com