我在Windows上使用Visual Studio 2015执行以下代码。基本上我使用std::get_time
来解析日期,但是当日期无效时,例如,一天大于31,似乎没有在流上设置失败位。Visual 2015上的std :: get_time在错误的日期没有失败
我在Ubuntu上用g ++ 5.4.0试过这个,它设置了失败位并打印出“解析失败!”。这是Windows上的错误还是我做错了什么。
在此先感谢!
std::string date = "2019-2-37 23:00:00"; // day (37) is wrong.
std::string format = "%Y-%m-%d %H:%M:%S";
std::tm tm_object{};
std::istringstream input(date);
input.imbue(std::locale(std::setlocale(LC_ALL, nullptr)));
input >> std::get_time(&tm_object, format.c_str());
if (input.fail())
{
std::cout << "Parsing failed!";
}
else
{
std::cout << "Parsing ok!\n";
std::cout << "Day is : " << tm_object.tm_mday;
}
感谢您的回答霍华德,您的图书馆为我工作! 无论如何,我仍然不明白为什么没有Windows的strptime函数或为什么std :: get_time没有验证日期在Visual 2015上是正确的。 – rboc
@rboc:很高兴为您效劳! 'strptime'不是标准的C++,而是由POSIX指定的。虽然'std :: get_time'是根据'strptime'指定的。 POSIX对'strptime'这样说:“没有错误被定义。” (http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html) –
是的,但至少strptime会在未完成(2月37日)时返回空指针。我期望std :: get_time在Visual Studio 2015上做类似的事情。 – rboc