13,825
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <boost/spirit.hpp>
#include <boost/spirit/phoenix.hpp>
using namespace std;
using namespace boost::spirit;
using namespace phoenix;
struct calc_closure : boost::spirit::closure<calc_closure, double>
{
member1 val;
};
const char* StrCalc(const char* s, double *out)
{
rule<phrase_scanner_t, calc_closure::context_t> factor, term, exp;
factor = real_p[factor.val = arg1] | ('(' >> exp[factor.val = arg1] >> ')');
term = factor[term.val = arg1] >> *(('*' >> factor[term.val *= arg1]) | ('/' >> factor[term.val /= arg1]));
exp = term[exp.val = arg1] >> *(('+' >> term[exp.val += arg1]) | ('-' >> term[exp.val -= arg1]));
parse_info<> r = parse( s , exp[assign_a(*out)], space_p);
return r.full? NULL : r.stop;
}
int main()
{
string s;
while(getline(cin,s) && s!="q")
{
double result;
const char* p = StrCalc(&s[0], &result);
if(p==NULL)
{
cout << " = " << result << endl;
}
else
{
cout << string(size_t(p - &s[0]), ' ') << '^' << endl;
}
}
return 0;
}