【问题标题】:boost ptime input_facet error with %f flag at converting string to ptime在将字符串转换为 ptime 时使用 %f 标志提升 ptime input_facet 错误
【发布时间】:2011-06-30 11:49:08
【问题描述】:

我在从字符串转换为 ptime 时读取时间分数时遇到问题。 以下是相关的源代码:

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

在格式字符串中没有 %f 时程序运行良好。但是 %f tgtDt 是“不是日期时间”。我使用 boost 1.44 并且文档说 %f shold 工作,因为每个输入不兼容的格式标志都标有“!”在文档中。

任何想法如何从字符串中取出 frac 部分?

【问题讨论】:

    标签: c++ boost time


    【解决方案1】:

    好的,想通了(知道它与点有关!).. 输入方面和输出方面需要不同的格式。请尝试以下操作:

    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() );
    

    【讨论】:

    • 不,同样的事情。您可以根据需要减少格式字符串。 "%H" 工作正常,"%f" 不行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多