我有以下代码来解决一个简单的算术表达式。我想修改为具有常量标识符的表达式运行它。 例如,以下代码适用于(2 * 3.14 * 5),但不适用于pi = 3.14的(2 * pi * 5)。 一种方法是首先解析字符串并在传递字符串之前进行查找和替换以提升精神。这可以在boost代码本身内完成。欢迎任何建议。 谢谢。
#include <boost/config/warning_disable.hpp>
#include "boost/spirit/include/qi.hpp"
#include "boost/spirit/include/phoenix_core.hpp"
#include "boost/spirit/include/phoenix_operator.hpp"
#include "boost/spirit/include/phoenix_stl.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
using qi::phrase_parse;
using qi::_1;
using ascii::space;
using phoenix::push_back;
using qi::double_;
template <typename Iterator>
struct calculator : qi::grammar<Iterator, double(), ascii::space_type>
{
calculator() : calculator::base_type(expression)
{
using qi::_val;
using qi::lexeme_d;
using qi::alpha_p;
using qi::alnum_p;
using qi::_1;
expression =
term [_val = _1]
>> *( ('+' >> term [_val += _1])
| ('-' >> term [_val -= _1])
)
;
term =
factor [_val = _1]
>> *( ('*' >> factor [_val *= _1])
| ('/' >> factor [_val /= _1])
)
;
factor =
double_ [_val = _1]
| '(' >> expression [_val = _1] >> ')'
| ('-' >> factor [_val = -_1])
| ('+' >> factor [_val = _1])
;
}
qi::rule<Iterator, double(), ascii::space_type> expression, term, factor;
};