【问题标题】:parse a date-time string into a time_t value with spirit用精神将日期时间字符串解析为 time_t 值
【发布时间】:2012-12-08 16:24:08
【问题描述】:

我需要使用boost::spirit2012-12-21 12:10:35 之类的日期时间字符串解析为time_t 值。这是我的代码 sn-p:

tc_     =   lexeme[int_[phx::ref(tm_.tm_year)=(_1-1900)]>>'-'
                     >>int_[phx::ref(tm_.tm_mon)=(_1-1)]>>'-'
                    >>int_[phx::ref(tm_.tm_mday)=_1]>>+space
                    >>int_[phx::ref(tm_.tm_hour)=_1]>>':'
                     >>int_[phx::ref(tm_.tm_min)=_1]>>':'
                    >>int_[phx::ref(tm_.tm_sec)=_1]]    [_val = (long)mktime(&tm_)];

其中tc_qi 类型的规则:qi::rule<Iterator, long(), Skipper>tm_struct tm 类型的成员变量。

代码编译,但不起作用。 mktime() 似乎根本没有被调用。我做错了什么?

【问题讨论】:

  • 感谢安迪的编辑。我是这里的新手..
  • 我可以添加附件吗?我想上传一个cpp文件以使问题更清楚。

标签: c++ parsing boost-spirit


【解决方案1】:

你可以在 c++ 11 vi 的正则表达式中做到这一点。 如果您的编译器足够新,这将是可移植的和标准的。

#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main()
{
    std::regex txt_regex("([0-9]{4})[-]([0-9]{2})[-]([0-9]{2})[ ]([0-9]{2})([:])([0-9]{2})([:])([0-9]{2})");//  
    string strTmp;
    strTmp="2010-12-15 15:25:46";
    std::smatch match;
    std::regex_search( strTmp, match, txt_regex );

    if(regex_match(strTmp,txt_regex))
         cout<<"Ok"<<endl;
    else
    {
    cout<<"Invalid input"<<endl;
    return 0;
    }
    if ( match.empty() )
    {
         std::cout << "...no more matches" << std::endl;
         return 0;
    }
    for ( auto x : match )
    {
        std::cout << "found: " << x << std::endl;
    }
    string str = match.suffix().str();
    cout <<str <<std::endl;
    return 0; 
}

这样你就可以显示要显示的字符串的不同部分,然后填充结构。

希望它有所帮助,并像往常一样向 cmets 开放(如果有不清楚或不完整的地方)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多