Evaluate an arithmetic expression given as a string

前端 未结 1 460
不知归路
不知归路 2021-01-29 06:51

I am working on a project where I need to calculate the value of an arithmetic expression given as string.

So that\'s the way I chose to use is such that I run the strin

相关标签:
1条回答
  • 2021-01-29 07:15
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct exp {
        char op;
        char *term;
        struct exp *left;
        struct exp *right;
    } Exp;
    
    Exp *make_exp2(char *str){
        if(!str || !*str) return NULL;//*str == '\0' is format error.
        char *mul = strrchr(str, '*');
        char *div = strrchr(str, '/');
        Exp *node = malloc(sizeof(*node));
        if(mul == NULL && div == NULL){
            node->op = '\0';
            node->term = str;
            node->left = node->right = NULL;
            return node;
        }
        char *op;
        op = mul < div ? div : mul;
        node->op = *op;
        *op = '\0';
        node->left  = make_exp2(str );
        node->right = make_exp2(op+1);
        return node;
    }
    
    Exp *make_exp(char *str){
        if(!str || !*str) return NULL;//*str == '\0' is format error.
        char *minus = strrchr(str, '-');
        char *plus  = strrchr(str, '+');
        if(minus == NULL && plus == NULL)
            return make_exp2(str);
        char *op;
        Exp *node = malloc(sizeof(*node));
        op = minus < plus ? plus : minus;
        node->op = *op;
        *op = '\0';
        node->left  = make_exp(str );
        node->right = make_exp(op+1);
        return node;
    }
    
    #ifdef DEBUG
    
    void print(Exp *exp, int level){
        int i;
        if(exp->op){
            for(i=0;i<level;++i)
                printf(" ");
            printf("%c\n", exp->op);
            for(i=0;i<level;++i)
                printf(" ");
            print(exp->right, level+1);
            printf("\n");
            for(i=0;i<level;++i)
                printf(" ");
            print(exp->left, level+1);
            printf("\n");
        } else {
            for(i=0;i<level;++i)
                printf(" ");
            printf("%s\n", exp->term);
        }
    }
    
    #endif
    
    int main(void) {
        char str[] = "3+1-4*6-7";
        Exp *exp = make_exp(str);
    
    #ifdef DEBUG
        print(exp, 0);
    #endif
        //release exp
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题