Boost logo

Boost :

Subject: Re: [boost] What else shall I do before reuse a stringstream for date parsing?
From: Dmitry Goncharov (dgoncharov_at_[hidden])
Date: 2009-02-16 04:12:37


Bill David wrote:
> To accelerate date parsing, I have writen a class to encapsulate the date
> parsing logic as following.
> But the second call to CDateParser::parseDate(str) always failed to parse
> the date string. What else shall I do before reuse the stringstream object?
>
> #include <stdio.h>
>
> #include <iostream>
> #include <sstream>
> using namespace std;
>
> #include "boost/date_time/posix_time/posix_time.hpp"
> using namespace boost::gregorian;
> using namespace boost::posix_time;
>
> class CDateParser
> {
> public:
> static void initialize();
> static time_t parseDate(const string& s);
> private:
> static stringstream m_ss; //!< stringstream object used internally for
> date parsing
> };
>
> stringstream CDateParser::m_ss;
>
> time_t CDateParser::parseDate(const string& str)
> {
> ptime p;
> m_ss.clear();
> m_ss << str;
> m_ss >> p;
> if (m_ss.fail()) {
> cout << "do not understand: " << str << endl;
> return 0;
> }
>
> tm t = to_tm(p);
> return mktime(&t);
> }
>
> void CDateParser::initialize() {
> time_input_facet* timefacet = new time_input_facet("%a, %d %b %Y
> %H:%M:%S %z"); // will be automatically deleted by related locale object
> m_ss.imbue(locale(locale::empty(), timefacet));
> }
>
> int main() {
> CDateParser::initialize();
>
> string str;
> time_t t;
>
> str = "Fri, 18 Jul 2008 11:53:14 GMT";
> t = CDateParser::parseDate(str);
> cout << ctime(&t) << endl;
>
> str = "Sat, 19 Jul 2008 11:53:14 GMT";
> t = CDateParser::parseDate(str);
> cout << ctime(&t) << endl;
> }
>
>

You should invoke m_ss.seekg(ios_base::beg) before each parsing.
Also, be careful with to_tm(). It is buggy. See
https://svn.boost.org/trac/boost/ticket/1859

BR, Dmitry


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk