C++ 捕获boost::ptime流上的错误

C++ 捕获boost::ptime流上的错误,c++,boost,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()))); o

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

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();
};
当我传递无效的
boostspec
字符串时,就会出现问题。函数中的第三行在进入
os.fail()
检查之前崩溃。我尝试捕捉所有我能想到的异常,但似乎找不到任何有效的。检查
boostspec
说明符字符串的有效性是此函数的关键目的

编辑:我正在使用boost 1.63和VS2012。
当boostspec=“%a%”时,它会可靠地崩溃-请注意空格

更新

MSVC的标准库实现中似乎存在错误。Boost默认情况下会将一些工作委托给:

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

很好。

你有一个导致它崩溃的bootspec示例吗?我无法复制它。(如果它引发异常,那不是崩溃,如果它崩溃,那就是定义上的错误)@sehe是的,谢谢!尝试类似“%a%%”的方法。请注意空格。我将检查一些较旧的boost版本,同时更改日志可能会提到一个相关的错误修复。我不认为我的boost很旧。我确信问题不在我自己代码的其他部分。这只会在VS 2012中留下一个错误-这不会让我感到惊讶。现在已经很晚了;明天我将尝试它n我的Linux服务器。非常感谢您的反馈!您如何确定问题不在其他地方?这在VS2012上会单独失败吗?(PS与boost 1.54无关:)我没有试过。但这是一个非常简单的片段。1.这很有趣,因为我复制/粘贴了你的复制机案例2。-也许你可以在调试器中发现库错误?
#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 % %”