我需要得到当前时间在“HH:MM:SS” -format到字符阵列(串),所以我可以用printf("%s", timeString);输出结果后简单地

我在timevaltime_t类型顺便说一句很困惑,因此,任何解释将是真棒:)

编辑: 所以,我想由strftime等,而且还挺奏效。这是我的代码:

time_t current_time;
struct tm * time_info;
char timeString[8];

time(&current_time);
time_info = localtime(&current_time);

strftime(timeString, 8, "%H:%M:%S", time_info);
puts(timeString);

但输出是这样的: “13:49:53A ?? J`aS”

什么与正在进行 “的的ΔΣJ`aS吗” 结尾?

有帮助吗?

解决方案

您是从这个代码让垃圾:

time_t current_time;
struct tm * time_info;
char timeString[8];

time(&current_time);
time_info = localtime(&current_time);

strftime(timeString, 8, "%H:%M:%S", time_info);
puts(timeString);

由于你不允许空间用于在串中的空终止(\ 0),所以当它打印的字符串,它不知道在哪里结束是和在存储器中作为一部分的下一个比特inteprets随机垃圾的字符串。

它更改为这样:

time_t current_time;
struct tm * time_info;
char timeString[9];  // space for "HH:MM:SS\0"

time(&current_time);
time_info = localtime(&current_time);

strftime(timeString, sizeof(timeString), "%H:%M:%S", time_info);
puts(timeString);

,它会正常工作,因为 strftime() 将有足够的空间来添加\ 0。请注意,我使用的sizeof(数组),以避免危险忘记改变在这两个地方的数目。

其他提示

看看在的strftime 的功能,它允许你写的时间到一个字符数组与您选择的格式。

#include <stdio.h>
#include <time.h>

/* get seconds since the Epoch */
time_t secs = time(0);

/* convert to localtime */
struct tm *local = localtime(&secs);

/* and set the string */
sprintf(timeString, "%02d:%02d:%02d", local->tm_hour, local->tm_min, local->tm_sec);

用于与时间处理(挂钟类型的时间,而不是进程/线程时间)的重要类型是time_tstruct tm。结果 一段时间的努力,你可以在一个和另一个之间进行转换,但是你必须要注意本地时间与UTC时间。

细读href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/time.h.html" rel="nofollow <time.h> 的noreferrer">描述神交时间用C

再次注意UTC时间和本地时间。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top