I am trying to run a very simple example of the std::get_time()
function but the parse is failing.
#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>
int main()
{
std::tm t = {};
std::istringstream ss("04-02-2022 3:04:32");
ss >> std::get_time(&t, "%m-%d-%Y %H:%M:%S");
if (ss.fail()) {
std::cout << "Parse failed\n";
if ((ss.rdstate() & std::istringstream::failbit) != 0)
std::cerr << "Error failbit\n";
if ((ss.rdstate() & std::istringstream::goodbit) != 0)
std::cerr << "Error goodbit\n";
if ((ss.rdstate() & std::istringstream::eofbit) != 0)
std::cerr << "Error eofbit\n";
if ((ss.rdstate() & std::istringstream::badbit) != 0)
std::cerr << "Error badbit\n";
}
else {
std::cout << std::put_time(&t, "%c") << '\n';
}
}
I am using Ubuntu 20.04 in Windows via WSL, which has g++ 9.4 installed, and I am compiling with the terminal command:
g++ -std=c++17 date.cpp -o date
The error is std::istringstream::failbit
Any Ideas what is going on?
I was able to reproduce the failure in gcc 9.4. It works if you change 3
to 03
in the hour field.
Even though %H
is not supposed to require a leading zero, this appears to be a gcc bug where it does. See Bug 78714. Despite being about %b
, this comment in that ticket goes into detail about how it also affects %H
and other placeholders, too.
The code works fine in gcc 12.1.
Demo