2

我想解析由 4 位数年份和年份中的周数组成的字符串。我遵循了 boost date/time IO 教程,生成了一个像这样的测试示例:

std::string week_format = "%Y-W%W";
boost::date_time::date_input_facet<boost::gregorian::date, char> week_facet =     boost::date_time::date_input_facet<boost::gregorian::date, char>(week_format);

std::stringstream input_ss;
input_ss.imbue(locale(input_ss.getloc(), &week_facet));

std::string input_week = "2004-W34";
input_ss.str(input_week);

boost::gregorian::date input_date;
input_ss >> input_date;

不幸的是,input_date只是打印为“2004-01-01”,这意味着它只是解析了年份。我究竟做错了什么?%W输入时不可用?(文档没有这样标记。)

4

1 回答 1

1

您是正确的,文档没有在“格式标志”部分中将其标记为这样(没有“!”旁边......)

http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.format_flags

但这似乎是一个疏忽。因为在 Boostformat_date_parser.hpp中没有涵盖这种情况parse_date...您可以查看 switch 语句并看到:

http://svn.boost.org/svn/boost/trunk/boost/date_time/format_date_parser.hpp

尽管没有任何代码可以做到这一点,即使源代码中的注释也说它处理 %W 和 %U 解析输入。那是怎么回事?:-/

另一方面,我相信 week_facet 需要在您的示例中动态分配:

std::string week_format = "%Y-W%W";
boost::date_time::date_input_facet<boost::gregorian::date, char>* week_facet =
    new boost::date_time::date_input_facet<boost::gregorian::date, char>(
        week_format
    );

std::stringstream input_ss;
input_ss.imbue(std::locale(input_ss.getloc(), week_facet));

(或者至少我必须这样做以防止示例崩溃。)

于 2011-11-01T05:48:43.203 回答