我想解析由 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
不可用吗? (文档没有这样标记。)
最佳答案
你是正确的,文档没有在“格式标志”部分中将其标记为这样(没有“!”旁边......)
http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.format_flags
但这似乎是一个疏忽。因为在 Boost 的 format_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));
(或者至少我必须这样做以防止示例崩溃。)
关于c++ - 如何使用 boost::date_time 解析一年中的几周?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7960801/