我刚刚开始深入研究 Boost::Spirit,目前的最新版本——V2.4。我的问题的本质如下:
我想解析像“1a2”或“3b4”这样的字符串。所以我使用的规则是:
(double_ >> lit('b') >> double_)
| (double_ >> lit('a') >> double_);
规则的属性必须是“vector <double>”。我正在将它读入容器中。
完整代码:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cstring>
int main(int argc, char * argv[])
{
using namespace std;
using namespace boost::spirit;
using namespace boost::spirit::qi;
using boost::phoenix::arg_names::arg1;
char const * first = "1a2";
char const * last = first + std::strlen(first);
vector<double> h;
rule<char const *, vector<double>()> or_test;
or_test %= (double_ >> lit('b') >> double_)
| (double_ >> lit('a') >> double_);
if (parse(first, last, or_test,h)) {
cout << "parse success: ";
for_each(h.begin(), h.end(), (cout << arg1 << " "));
cout << "end\n";
} else cout << "parse error\n" << endl;
return 0;
}
我正在用 g++ 4.4.3 编译它。它返回“1 1 2”。虽然我期待“1 2”。
据我了解,这是因为解析器:
- 去第一个选择
- 读取一个 double_ 并将其存储在容器中
- 然后停在 "a",同时期待 lit("b")
- 转到第二种选择
- 再读两个双打
我的问题是——这是一个正确的行为吗?如果是——为什么?