boost ptime input_facet error with %f flag at converting string to ptime
I have problems with reading the time fraction at converting from string to ptime. Here is the regarding soruce code:
#include <iostream>
#include <string>
#include <boost/date_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/conversion.hpp>
int main( int, char * )
{
using namespace std;
using namespace boost;
using namespace boost::posix_time;
using namespace boost::local_time;
using namespace boost::gregorian;
time_facet* output_facet = new time_facet();
time_input_facet* input_facet = new time_input_facet();
stringstream sstream;
sstream.imbue(locale(locale::classic(), output_facet));
sstream.imbue(locale(sstream.getloc() , input_facet ));
string format("%d/%m/%Y %H:%M:%S.%f"); //example works fine without %f!!!
//format = "%H"; //-> works
//format = "%f"; //-> error
output_facet->format( format.c_str() );
input_facet->format( format.c_str() );
ptime开发者_开发百科 dt = microsec_clock().local_time();
sstream.str("");
sstream << dt;
cout << sstream.str() << endl;
string time_string = sstream.str();
ptime tgtDt( boost::date_time::not_a_date_time );
sstream.str( time_string.c_str() );
sstream >> tgtDt;
cout << tgtDt << endl;
}
The program runs fine without the %f inside the format string. But with %f tgtDt is "not-a-date-time". I use boost 1.44 and the doc says %f shold work, because every input incompatible format flag is marked with "!" in the documentation.
Any ideas how to get the frac part out of a string?
Ok, figured it out (knew it had something to do with the dot!).. The input facet and output facet expect different formats.. try the following:
string inputformat("%d/%m/%Y %H:%M:%S%f"); //no dot before %f
string format("%d/%m/%Y %H:%M:%S.%f"); //dot before %f
output_facet->format( format.c_str() );
input_facet->format( inputformat.c_str() );
精彩评论