代码之家  ›  专栏  ›  技术社区  ›  bers

为什么get\u time无法解析put\u time生成的内容?

  •  0
  • bers  · 技术社区  · 4 年前

    我使用得到错误的结果 get_time 使用 PM 修改器。

    为了确保我使用了正确的修饰符(即使它根本不应该取决于语言环境),我使用 put_time 在此示例代码中:

    #include <iostream>
    #include <sstream>
    #include <iomanip>
    
    using namespace std;
    
    int main() {
        // Initialize time from 24-format
        tm tm;
        strptime("16:33:45", "%H:%M:%S", &tm);
    
        // Define 12h time format
        string fmt("%I:%M:%S%p");
    
        // Convert time to 12h format and print - looks good!
        ostringstream oss;
        oss << put_time(&tm, fmt.c_str());
        cout << oss.str() << endl;
    
        // Read time in 12h format
        istringstream iss(oss.str());
        iss >> get_time(&tm, fmt.c_str());
    
        // Result is wrong!
        cout << iss.fail() << " (Fail)" << endl;
        cout << tm.tm_hour << endl;
    
        // Read time in 12h format using strptime
        strptime(iss.str().c_str(), fmt.c_str(), &tm);
    
        // Result is correct!
        cout << "Correct" << endl;
        cout << tm.tm_hour << endl;
    }
    

    输出:

    04:33:45PM
    1 (Fail)
    4
    Correct
    16
    

    另请参见 https://coliru.stacked-crooked.com/view?id=c4f75f14fdf53095

    我在2018年遇到了一个(未经证实的)GCC错误,其内容非常相似,即, https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84216 。还有,我发现 is this a bug in std::get_time? 根据唯一的答案,这与我不知道使用的某些Microsoft实现有关。

    strptime 能够正确解析时间。

    这是某个地方的bug,还是我在使用 get\u时间 不正确?

    0 回复  |  直到 4 年前