【发布时间】:2014-05-27 23:35:20
【问题描述】:
我有一个格式如下的文件
metal 1 1.2 2.2
wire 1.1 2.3
metal 2 3.2 12.2
...
这是一种非常简单的格式。 “金属”和“电线”是关键字。 “metal”后面是 1 uint 和 2 double,而“wire”后面是 2 double。 我尝试使用 Boost::Qi 来解析它,但结果很奇怪,我不知道为什么。
#include <iostream>
#include <string>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/phoenix_bind.hpp>
#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
using std::cout;
using std::endl;
using std::string;
using namespace boost::spirit;
namespace client
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace spirit = boost::spirit;
namespace phoenix = boost::phoenix;
// grammar
template <typename Iterator>
struct TimingLibGrammar :
qi::grammar<Iterator, ascii::space_type>
{
qi::rule<Iterator, ascii::space_type> expression;
TimingLibGrammar() : TimingLibGrammar::base_type(expression)
{
using qi::uint_;
using qi::int_;
using qi::double_;
using qi::char_;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_val;
using qi::lexeme;
using qi::lit;
expression =
+(
((
"metal"
>> uint_
>> double_
>> double_)[cout << "metal" << " "<< _1 << " " << _2 << " " << _3 << endl])
|
((
"wire"
>> double_
>> double_)[cout << "wire" << " "<< _1 << " " << _2 << endl])
);
}
};
}
int main()
{
using boost::spirit::ascii::space;
using namespace client;
string str = "metal 3 1.0 2.0";
TimingLibGrammar<string::const_iterator> tlg;
string::const_iterator iter = str.begin();
string::const_iterator end = str.end();
client::qi::phrase_parse(iter, end, tlg, space);
return 0;
}
代码的主要部分实际上很短。请忽略那些无用的包含。
当我尝试解析一行时
metal 3 1.0 2.0,
解析器给我的结果如下:
wire metal 3 1 2
这个结果不正确。它应该输出“metal 3 1 2”,但我不知道这个“wire”是从哪里来的。我还尝试遵循 boost 库中的几个示例代码。但它仍然未能正确处理。 代码使用带有 -std=c++11 标志的 g++ 4.7.2 编译。
任何建议都会有所帮助。我是提振精神的新手,所以我希望能学到一些东西。提前致谢。
【问题讨论】:
标签: c++ boost-spirit boost-spirit-qi