【问题标题】:Parsing a list of doubles with boost::spirit使用 boost::spirit 解析双打列表
【发布时间】:2012-02-24 10:25:55
【问题描述】:

这是一个代码示例。

// file temp.cpp

#include <iostream>

#include <vector>
#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

struct parser : qi::grammar<std::string::const_iterator, std::vector<double> >
{
    parser() : parser::base_type( vector )
    {
        vector  = +qi::double_;
    }

    qi::rule<std::string::const_iterator, std::vector<double> > vector;
};

int main()
{
    std::string const x( "1 2 3 4" );
    std::string::const_iterator b = x.begin();
    std::string::const_iterator e = x.end();
    parser p;
    bool const r = qi::phrase_parse( b, e, p, qi::space );
    // bool const r = qi::phrase_parse( b, e, +qi::double_, qi::space ); // this this it PASSES
    std::cerr << ( (b == e && r) ? "PASSED" : "FAILED" ) << std::endl;
}

我想用parser p 解析std::string x

struct parser的定义如下,行

qi::phrase_parse( b, e, p, qi::space ); // PASSES

qi::phrase_parse( b, e, +qi::double_, qi::space ); // FAILS

应该是等价的。但是,第一个解析失败,第二个解析通过。

struct parser 的定义我做错了什么?

【问题讨论】:

    标签: c++ parsing attributes boost-spirit boost-spirit-qi


    【解决方案1】:

    您应该“告知”有关跳过空格的语法 - 模板中的另一个参数。

    #include <iostream> 
    
    #include <vector> 
    #include <boost/spirit/include/qi.hpp> 
    
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;
    
    struct parser
      : qi::grammar<std::string::const_iterator, std::vector<double>(), ascii::space_type> 
    { 
      parser() : parser::base_type( vector ) 
      { 
        vector  %= +(qi::double_); 
      } 
    
      qi::rule<std::string::const_iterator, std::vector<double>(), ascii::space_type> vector;
    }; 
    
    int main() 
    { 
      std::string const x( "1 2 3 4" ); 
      std::string::const_iterator b = x.begin(); 
      std::string::const_iterator e = x.end(); 
      parser p; 
      bool const r = qi::phrase_parse( b, e, p, ascii::space ); 
      //bool const r = qi::phrase_parse( b, e, +qi::double_, qi::space );
      std::cout << ( (b == e && r) ? "PASSED" : "FAILED" ) << std::endl; 
    } 
    

    我还做了一些小的更正,例如你应该在参数中添加括号,它告诉属性类型:std::vector&lt;double&gt;()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 2013-08-24
      相关资源
      最近更新 更多