我有一个返回格式化日期/时间字符串的函数。实际日期和时间是恒定的;这是我所追求的结果字符串的格式。
std::string example_datetime(const std::string &boostspec)
{
std::ostringstream os;
os.imbue(std::locale(std::locale::classic(), new boost::posix_time::time_facet(boostspec.c_str())));
os << boost::posix_time::time_from_string("2014-02-13 08:30:00.000");
return os.fail() ? "invalid specifier" : os.str();
};
我会像这样使用这个函数:
std::string str(example_datetime("%a %b %d, %Y, %H:%M:%S"));
我遇到的问题发生在我传递无效的 boostspec
字符串时。在到达 os.fail()
检查之前,函数中的第 3rd 行崩溃了。我已经 try catch 所有我能想到的异常,但似乎找不到任何有用的东西。检查 boostspec
说明符字符串的有效性是此函数的一个关键目的。
编辑:我使用的是 boost 1.63 和 VS2012。 当 boostspec = “%a % “- 注意空格
最佳答案
更新
看起来 MSVC 的标准库实现中存在错误。 Boost 将一些工作委托(delegate)给 std::time_put<>
默认情况下:
Live On http://rextester.com/TMXPG58348
#include <ctime>
#include <iomanip>
#include <iostream>
int main() {
try {
// std::locale::global(std::locale("de_DE.utf8"));
std::time_t t = std::time(NULL);
std::tm tm = *std::localtime(&t);
std::string const fmt = "%a % ";
std::use_facet<std::time_put<char> >(std::cout.getloc())
.put({ std::cout }, std::cout, ' ', &tm, fmt.data(), fmt.data() + fmt.size());
} catch(...) {
std::cerr << "An exception was raised\n";
}
}
结果
您的问题可能出在其他地方:
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
std::string example_datetime(const std::string &boostspec)
{
std::ostringstream os;
os.imbue(std::locale(std::locale::classic(), new boost::posix_time::time_facet(boostspec.c_str())));
os << boost::posix_time::time_from_string("2014-02-13 08:30:00.000");
return os.fail() ? "invalid specifier" : os.str();
}
int main() {
std::cout << example_datetime("%a % %") << std::endl;
std::cout << example_datetime("“%a % %”") << std::endl;
}
打印
Thu %
“Thu % %”
很好。
关于c++ - 在 boost::ptime 流上捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47193865/