小编Pab*_*ggi的帖子

两位数年份的 get_time 解析错误

当格式包含“%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;
}

Run Code Online (Sandbox Code Playgroud)

输出:

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

c++ gcc clang libstdc++

7
推荐指数
1
解决办法
418
查看次数

标签 统计

c++ ×1

clang ×1

gcc ×1

libstdc++ ×1