使用boost :: spirit解析双精度列表

时间:2012-02-24 10:25:55

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

这是一个代码示例。

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

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

struct parser的定义所示,行

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

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

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

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

1 个答案:

答案 0 :(得分:2)

你应该“通知”关于跳过空格的语法 - 模板中的另一个参数。

#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<double>()