使用HH:MM:SS格式(C编程)进入字符串的时间

o01*_*o01 6 c string time time-t

我需要将"HH:MM:SS"格式的当前时间转换为字符数组(字符串),以便稍后我可以输出结果 printf("%s", timeString);

我对btw 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);
Run Code Online (Sandbox Code Playgroud)

但输出是这样的:"13:49:53a ?? J`aS?"

最后" a ?? J`aS? "发生了什么?

Joh*_*ter 10

你从这段代码得到了垃圾:

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);
Run Code Online (Sandbox Code Playgroud)

因为你不允许在字符串上使用空终止符(\ 0),所以当它打印的字符串时,它不知道结尾的位置,并在下一位内存中作为字符串的一部分解释随机垃圾.

把它改成这个:

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);
Run Code Online (Sandbox Code Playgroud)

并且它将正常工作,因为strftime()它将有足够的空间来添加\ 0.请注意,我正在使用sizeof(数组)来避免忘记更改两个地方的数字的风险.


sep*_*p2k 5

看一下strftime函数,它允许您将时间写入具有您选择格式的char数组中.