2012-12-21 27 views
2

我需要使用boost::spirit将日期时间字符串如2012-12-21 12:10:35解析为time_t值。这里是我的代码片段:用精神解析日期时间字符串到time_t值

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()根本没有被调用。我究竟做错了什么?

+0

感谢Andy的编辑。我是一个新手.. – napie

+0

我可以添加附件吗?我想上传一个cpp文件来使问题更清楚。 – napie

回答

0

你可以在C++ 11中使用正则表达式。 如果你的编译器足够近,这将是可移植的和标准的。

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

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

希望它像往常一样帮助和打开评论(如果有什么不清楚或不完整)。