黄舟2017-04-17 11:55:06
直接贴个以前写过的给你吧。
#include <iostream>
#include <boost/algorithm/string/trim.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
typedef double value_t;
template <typename Iterator>
struct calc_parser : boost::spirit::qi::grammar<Iterator, value_t(), boost::spirit::ascii::space_type> {
calc_parser() : calc_parser::base_type(expression) {
using boost::spirit::qi::double_;
using boost::spirit::qi::_val;
using boost::spirit::qi::_1;
expression = term [_val=_1]
>> *( ('+' >> term [_val=_val+_1])
| ('-' >> term [_val=_val-_1])
)
;
term = factor [_val=_1]
>> *( ('*' >> factor [_val=_val*_1])
| ('/' >> factor [_val=_val/_1])
)
;
factor = double_ [_val=_1]
| '(' >> expression [_val=_1] >> ')'
| ('+' >> factor [_val=_1])
| ('-' >> factor [_val=-_1])
;
}
boost::spirit::qi::rule<Iterator, value_t(), boost::spirit::ascii::space_type> expression;
boost::spirit::qi::rule<Iterator, value_t(), boost::spirit::ascii::space_type> term;
boost::spirit::qi::rule<Iterator, value_t(), boost::spirit::ascii::space_type> factor;
};
int main() {
using boost::spirit::ascii::space;
typedef std::string::const_iterator iterator_type;
calc_parser<iterator_type> calc;
std::string line;
while (std::getline(std::cin, line)) {
boost::trim(line);
if(line=="quit") break;
iterator_type first=line.cbegin();
iterator_type last=line.cend();
value_t v;
bool r=phrase_parse(first, last, calc, space, v);
if (r && first==last) {
std::cout << v << std::endl;
} else {
std::cout << "Parse error" << std::endl;
}
}
return 0;
}