【发布时间】:2022-01-12 04:28:15
【问题描述】:
当格式包含“%y”或“%Y”时,std::get_time 的行为方式相同,在这两种情况下,它都会尝试读取四位数的年份。我做错了什么还是一个错误?
示例代码:
#include <iostream>
#include <iomanip>
void testDate(const char *format,const char *date)
{
std::istringstream ds(date);
std::tm tm = {};
ds >> std::get_time(&tm,format);
std::cout<<date<<" parsed using "<<format<<" -> Year: "<<tm.tm_year+1900<<" Month: "<<tm.tm_mon<<" Day: "<<tm.tm_mday<<std::endl;
}
int main()
{
testDate("%y%m%d","101112");
testDate("%Y%m%d","101112");
testDate("%y%m%d","20101112");
testDate("%Y%m%d","20101112");
return 0;
}
输出:
101112 parsed using %y%m%d -> Year: 1011 Month: 11 Day: 0
101112 parsed using %Y%m%d -> Year: 1011 Month: 11 Day: 0
20101112 parsed using %y%m%d -> Year: 2010 Month: 10 Day: 12
20101112 parsed using %Y%m%d -> Year: 2010 Month: 10 Day: 12
测试:
g++ (SUSE Linux) 11.2.1 20210816 [修订版 056e324ce46a7924b5cf10f61010cf9dd2ca10e9]
clang++ 版本 12.0.1
【问题讨论】:
-
我实际上依赖于这个,但我有一个解决方法。我将来会需要它,所以找出发生了什么会很棒。我认为这是错误,但我不想和每个人一起检查。我试图查看源代码,但我很难在 gcc 树中找到“实际”实现。
-
是的,我可以想象这是一个相当大的兔子洞的潜水。如果是我,我会推出自己的解决方法,根本不依赖它。如果不是错误,那绝对是一个怪癖。通过在格式中添加任何非数字字符,它当然可以工作。看起来
year正在被一种贪心算法解析,这向我表明标准库可能会调用get_year作为后备。也许该代码中某处有// TODO注释;)