Equation (expression) parser with precedence?

前端 未结 23 1797
遇见更好的自我
遇见更好的自我 2020-11-22 11:44

I\'ve developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &, *, /, etc) operators, unary (!) operators, and parenthesis.

<
23条回答
  •  余生分开走
    2020-11-22 12:13

    Another resource for precedence parsing is the Operator-precedence parser entry on Wikipedia. Covers Dijkstra's shunting yard algorithm, and a tree alternate algorithm, but more notably covers a really simple macro replacement algorithm that can be trivially implemented in front of any precedence ignorant parser:

    #include 
    int main(int argc, char *argv[]){
      printf("((((");
      for(int i=1;i!=argc;i++){
        if(argv[i] && !argv[i][1]){
          switch(argv[i]){
          case '^': printf(")^("); continue;
          case '*': printf("))*(("); continue;
          case '/': printf("))/(("); continue;
          case '+': printf(")))+((("); continue;
          case '-': printf(")))-((("); continue;
          }
        }
        printf("%s", argv[i]);
      }
      printf("))))\n");
      return 0;
    }
    

    Invoke it as:

    $ cc -o parenthesise parenthesise.c
    $ ./parenthesise a \* b + c ^ d / e
    ((((a))*((b)))+(((c)^(d))/((e))))
    

    Which is awesome in its simplicity, and very understandable.

提交回复
热议问题