Evaluating arithmetic expressions from string in C++

匿名 (未验证) 提交于 2019-12-03 02:11:02

问题:

I'm searching for a simple way to evaluate a simple math expression from an string, like this:

3*2+4*1+(4+9)*6

I just want + and * operations plus ( and ) signs. And * has more priority than +.

回答1:

I think you're looking for a simple recursive descent parser.

Here's a very simple example:

const char * expressionToParse = "3*2+4*1+(4+9)*6";  char peek() {     return *expressionToParse; }  char get() {     return *expressionToParse++; }  int expression();  int number() {     int result = get() - '0';     while (peek() >= '0' && peek() = '0' && peek() 


回答2:

One can try : http://partow.net/programming/exprtk/index.html

  1. very simple
  2. only need to include "exprtk.hpp" to your source code.
  3. you can change the value of variables of the expression dynamically.
  4. good starting point: http://partow.net/programming/exprtk/code/exprtk_simple_example_01.cpp


回答3:

Just to add another alternative, consider trying TinyExpr for this problem. It's open source and self-contained in one source code file. It is actually written in C, but it will compile cleanly as C++ in my experience.

Solving your example expression from above is as simple as:

#include "tinyexpr.h" #include   int main() {     double answer = te_interp("3*2+4*1+(4+9)*6", 0);     printf("Answer is %f\n", answer);     return 0; } 


回答4:

While searching a library for a similar task I found libmatheval. Seems to be a proper thing. Unfortunately, GPL, which is unacceptable for me.



回答5:

import java.util.Deque; import java.util.LinkedList;   public class EvaluateArithmeticExpression {     public static void main(String[] args) {         System.out.println(evaluate("-4*2/2^3+3")==-4*2/Math.pow(2, 3)+3);         System.out.println(evaluate("12*1314/(1*4)+300")==12*1314/(1*4)+300);         System.out.println(evaluate("123-(14*4)/4+300")==123-(14*4)/4+300);         System.out.println(evaluate("12*4+300")==12*4+300);     }     public static int evaluate(String s){         Deque vStack= new LinkedList();         Deque opStack= new LinkedList();         int i=0;         while(i vStack,int i){         int sign=1;         if(s.charAt(i)=='-' || s.charAt(i)=='+')             sign=s.charAt(i++)=='-'?-1:1;         int val=0;         while(i opStack,Deque vStack,int i){         char op=s.charAt(i);         if(op=='(')             opStack.push(op);         else{             if(op==')'){                 while(!opStack.isEmpty() && opStack.peekFirst()!='(')                     doOp(opStack,vStack);                 opStack.pop();             }             else{                 while(!opStack.isEmpty() && prior(op) opStack,Deque vStack){         int b=vStack.isEmpty()?0:vStack.pop();         int a=vStack.isEmpty()?0:vStack.pop();         char op=opStack.pop();         int res=evaluate(a,b,op);         vStack.push(res);     }     private static int evaluate(int a, int b, char op){         switch(op){             case '+': return a+b;             case '-': return a-b;             case '/': return a/b;             case '*': return a*b;             case '^': return (int)Math.pow(a,b);         }         return 0;     }     private static boolean isNum(String s, int i){         return '0'


回答6:

I've written a very simple expression evaluator in C# (minimal changes required to make it C++-compliant). It is based on expression tree building method, only that tree is not actually built but all nodes are evaluated in-place.

You can find it on this address: Simple Arithmetic Expression Evaluator



回答7:

I think you can find the answer in this post: Evaluating string "3*(4+2)" yield int 18

Or you can give a try to this library: http://weblogs.asp.net/pwelter34/archive/2007/05/05/calculator-net-calculator-that-evaluates-math-expressions.aspx



回答8:

Here's a nice little presentation on evaluation trees for complex (not really :p) mathematical expressions:

http://courses.cs.vt.edu/~cs1044/spring01/cstruble/notes/6.complexexpr.pdf

It'll walk you through it in style ;)



回答9:

Consider using boost spirit:

http://www.boost.org/doc/libs/1_35_0/libs/spirit/example/fundamental/ast_calc.cpp



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!