I have the following piece of code for solving a simple arithmetic expression. I want to modify to run it for expressions with constant identifiers. For example, the following code will work for (2 *3.14 * 5), but will not work for (2*pi* 5) where pi =3.14. One way to handle is to first parse the string and do a find and replace before passing the string to boost spirit. Can this be done inside the boost code itself. Any suggestions are welcome. Thanks.
#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;
};