如何c++ 计算字符串表达式的值
PHPz
PHPz 2017-04-17 11:53:06
0
3
660

除了逆波兰式求解 字符串表达式之外,还有其他什么方法来求值?

PHPz
PHPz

学习是最好的投资!

Antworte allen(3)
阿神

不少方法啊 表达式树,两个栈(操作数栈,运算符栈),文法等等

黄舟

直接贴个以前写过的给你吧。

#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;
}
黄舟

这个我也不懂,帮不了你

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage