c++ - 在将字符串转换为 ptime 时使用 %f 标志 boost ptime input_facet 错误

标签 c++ boost time

我在读取从字符串转换为 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 应该有效,因为每个输入不兼容格式标志都标有“!”在文档中。

有什么想法如何从字符串中取出 frac 部分吗?

最佳答案

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

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

关于c++ - 在将字符串转换为 ptime 时使用 %f 标志 boost ptime input_facet 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6534248/

相关文章:

C++ 编译器错误 "cannot be thread-local because it has non-POD type”“

c++ - 没有 Boost 的 BOOST_DEDUCED_TYPENAME 的实现

c++ - boost msm - boost msm 多个延迟事件

c++ - Unix 函数 gmtime_r 的 Windows 等价物是什么?

node.js - NodeJS 在计算质数时比 D 更快。如何?

c++ - SORT 整数数组 TAG 结构数组(或两个)

c++ - 将 boost::bind 与 boost::function 一起使用:检索绑定(bind)变量类型

c++ - 在 tee.hpp 中 boost 断言 'result1 ==n && result2 == n'

ruby-on-rails - DateTime 类的意义何在?

c++ - C 和 C++ 中的多字 rune 字