c++ - 在 boost::ptime 流上捕获错误

标签 c++ boost

我有一个返回格式化日期/时间字符串的函数。实际日期和时间是恒定的;这是我所追求的结果字符串的格式。

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";
    }
}

结果

enter image description here

您的问题可能出在其他地方:

Live On Coliru

#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/

相关文章:

c++ - 优化这个功能?

c++ - 查找输出流的当前基

c++ - 如何将有向图(邻接表)传递给 Dijkstra 算法 boost 以找到最短路径?

c++ - Boost::thread 如何在主线程和工作线程之间同步?

c++ - 如何在boost共享内存中直接写入opencv cv::Mat图像

VS2012 C++类特殊成员函数默认并删除

c# - 无法加载 DLL 找不到指定的模块。 (来自 HRESULT : 0x8007007E) 的异常

c++ - OpenGL glBufferData -> 为什么 &vertices[0] 而不是 &vertices 作为数据参数?

c++ - 具有非连续存储(即!= vecS)和 add_edge() 的最小 boost adjacency_list

c++ - 无法使用 Boost GIL 检测图像文件类型(未捕获异常)