c++ - 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));
如果格式文本不正确,如何阻止应用程序崩溃?
解决方案
看来,您正在从外部获取格式字符串,可能来自用户输入。
所以你不能让你的 strftime 不崩溃,你必须在调用 strftime 之前验证格式字符串。
例如,您可以:
使用正则表达式查找所有序列,如
“%[^aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%]”
(格式字母取自这里:http ://www.cplusplus.com/reference/ctime/strftime/ )如果您找到了这样的子字符串,您只需不运行 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”这样的函数来方便地在程序中的任何地方使用它
推荐阅读
- python - 如何使变量等于多个字符串?
- pip - 我在 Mac 上安装了 pip 和 conda。现在管理python包的最佳方法是什么?
- javascript - Javascript,将复选框与 JSON 匹配
- python - 如何解决“ImmutableDenseNDimArray”对象没有属性“could_extract_minus_sign”?
- z3 - 证明溢出检查表达式是正确的
- c# - VB.NET Service.OnStart() 从不调用
- android - Android Material Component BottomNavigation 顶部阴影放置在底部时与居中时不同
- c - 当我用新指针分配指针而没有空闲时,这是不好的做法吗?
- android - 应用插件如何在 gradle 中工作
- sql - 创建单独表的权宜之计