我有以下代码将日期转换为毫秒:

long lond dateToMs(const char* text)
{
     std::tm tm = {};
     const char* snext = ::strptime(text, "%d-%m-%Y %H:%M:%S", &tm);
     auto time_point = std::chrono::system_clock::from_time_t(std::mktime(&tm));
     return time_point.time_since_epoch() / std::chrono::milliseconds(1) + std::atof(snext) * 1000.0f;
}

当我有一个不存在的日期时,例如:40-10-2015 12:23:45.2354,程序显示以下消息:Segmentation fault (core dumped)相反,我想显示类似The introduced date it's not valid的内容。
我已经尝试过try..catch块,如下所示:
long long dateToMs(const char* text)
{
 try{
  std::tm tm = {};
  const char* snext = ::strptime(text, "%d-%m-%Y %H:%M:%S", &tm);
  auto time_point = std::chrono::system_clock::from_time_t(std::mktime(&tm));
  return time_point.time_since_epoch()/std::chrono::milliseconds(1)+std::atof(snext)*1000.0f;
 }
 catch(const std::exception &)
 {
    std::cout << "The introduced date it's not valid" << std::endl;
 };
}

但是它显示了相同的错误:Segmentation fault (core dumped),我必须做些什么才能显示所需的消息错误。

最佳答案

您没有考虑snext为null的可能性。

long long dateToMs(const char* text)
{
     std::tm tm = {};
     const char* snext = ::strptime(text, "%d-%m-%Y %H:%M:%S", &tm);
     if ( snext )
     {
          auto time_point = std::chrono::system_clock::from_time_t(std::mktime(&tm));
          return time_point.time_since_epoch() / std::chrono::milliseconds(1) + std::atof(snext) * 1000.0f;
     }
     else
     {
          std::cout << "The introduced date it's not valid";
     }


}

Live sample

07-24 09:44
查看更多