gpt4 book ai didi

c - strptime() 在 C 中产生垃圾时间

转载 作者:行者123 更新时间:2023-12-03 08:13:56 25 4
gpt4 key购买 nike

我尝试使用 strptime() 解析 ISO 8601 格式的日期(由“%F”或“%Y-%m-%d”指定),但是当我从结果 struct tm 中读取时,我得到了荒谬的值时间、分钟和秒。这是示例代码和结果:

char *s_date = (char *)malloc(sizeof(char) * 255);
scanf("%s", s_date);

struct tm bd_date;
strptime(s_date, "%Y-%m-%d", &bd_date)

printf("%d-%d-%d %d:%d:%d\n", (bd_date.tm_year + 1900), (bd_date.tm_mon + 1), bd_date.tm_mday, bd_date.tm_hour, bd_date.tm_min, bd_date.tm_sec);

输入“1990-05-01”的结果输出是:1990-5-1 2007659173:32766:1076394855,显示 tm_hour、tm_min 和 tm_sec 的非法值。我究竟做错了什么?我有什么遗漏的吗?我虽然 strptime() 会自动将格式中未使用的字段设置为 0,但情况似乎并非如此。

最佳答案

Apple 的 strptime 手册页明确表示:

If the <i>format</i> string does not contain enough conversion specifications to completely specify the resulting <i>struct tm</i>, the unspecified members of <i>timeptr</i> are left untouched. For example, if format is “%H:%M:%S”, only <i>tm_hour</i>, <i>tm_sec</i> and <i>tm_min</i> will be modified.

Linux man pages不那么明确,但与此一致:

In principle, this function does not initialize <i>tm</i> but stores only the values specified. This means that <i>tm</i> should be initialized before the call.

Apple 的 macOS 和 Linux 都力求遵守的 POSIX 标准,在我手头上的 2008 年版本中既没有上述内容,也没有类似的文本。对于其他结构成员是否被修改或结构是否被初始化,它只是保持沉默。

因此,至少在某些实现中,strptime不修改格式字符串中没有相应描述符的成员。例如,如果没有小时描述符,例如 %H ,它不会修改结构体的 hour 成员。如果您想要设置这些成员,您可以在调用 strptime 之前设置它们。 .

关于c - strptime() 在 C 中产生垃圾时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70059813/

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