首页 > 解决方案 > std::strftime 因输入错误而崩溃

问题描述

这就是我使用该函数提取日期和时间的方式。

std::strftime(&stdstrSystemTime[0], stdstrSystemTime.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now));

但是如果格式文本的格式不正确,应用程序会崩溃,例如

std::strftime(&stdstrSystemTime[0], stdstrSystemTime.size(), "%Y-%m-%d %:%M:%S", std::localtime(&now));

如果格式文本不正确,如何阻止应用程序崩溃?

标签: c++time

解决方案


看来,您正在从外部获取格式字符串,可能来自用户输入。

所以你不能让你的 strftime 不崩溃,你必须在调用 strftime 之前验证格式字符串。

例如,您可以:

  1. 使用正则表达式查找所有序列,如
    “%[^aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%]”
    (格式字母取自这里:http ://www.cplusplus.com/reference/ctime/strftime/ )

  2. 如果您找到了这样的子字符串,您只需不运行 strftime 并给您的用户错误消息,例如“错误!输入错误!” 并且可能是格式字符串中错误的位置。

为此,您可以使用标准库http://www.cplusplus.com/reference/regex/basic_regex/basic_regex/中的 regex_match

#include <regex>
#include <string>
...
// defining regex pattern:
std::string pattern = "%[^aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%]";
...
// user_format - is a variable with possible wrong date format
// if regexp didn't match then...
if (! std::regex_match (user_format, std::regex(pattern)))
{
    // run your code!
    std::strftime(&stdstrSystemTime[0], stdstrSystemTime.size(), user_format, std::localtime(&now));
}
else
{
    // lets pretend returning false means an error
    return false;
}

也许这个例子并没有涵盖所有的案例,它只是一个草稿。但我想你明白了。此外,最好有一个像“validate_date_format”这样的函数来方便地在程序中的任何地方使用它


推荐阅读