Parsing mathematical expressions with two values that have parentheses and minus signs

cparsing

I'm trying to parse equations like the ones below, which only have two values or the square root of a certain value, from a text file:

100+100

-100-100

-(100)+(-100)

sqrt(100)

by the minus signs, parentheses and the operator symbol in the middle and the square root, and I have no idea how to start off… I've got the file part done and the simple calculation parts except that I couldnt get my program to solve the equations in the above.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

main(){
    FILE *fp;
    char buff[255], sym,sym2,del1,del2,del3,del4;
    double num1, num2;
    int ret;
    fp = fopen("input.txt","r");

    while(fgets(buff,sizeof(buff),fp)!=NULL){
        char *tok = buff;
        sscanf(tok,"%lf%c%lf",&num1,&sym,&num2);

        switch(sym){
            case '+': printf("%lf\n", num1+num2);
                    break;
            case '-': printf("%lf\n", num1-num2);
                    break;
            case '*': printf("%lf\n", num1*num2);
                    break;
            case '/': printf("%lf\n", num1/num2);
                    break;
            default: printf("The input value is not correct\n");
                    break;
        }
    }
    fclose(fp);
}

That is what I have written for the other basic operations without parentheses and the minus sign for the second value and it works great for the simple ones. I'm using a switch statement to calculate the add, sub, mul and div operations but I'm not sure how to properly use the sscanf function (if I am not using it properly) or if there is another way, such as using a function like strtok to properly parse the parentheses and the minus signs. Any kind help?

Best Answer

Parsing expressions, with parentheses and unequal operator precedence, is THE standard parsing example in just about every compiler textbook in existence. Function calls aren't USUALLY part of that example, but they are simple enough to add. Rather than go trial-and-error, your life will be a lot easier in the long run if you learn how to do it for real.

The most accessible introduction to building hand-constructed parsers I have seen is Jack Crenshaw's "Let's Build A Compiler".

The most accessible textbook I've seen on compiler construction is Wirth's "Compiler Construction". It describes hand-coded recursive descent parsing.

The canonical references on compiler construction are the various Dragon Books. I personally used the Green Dragon Book and found it usable, although the focus is on mechanically-generated LALR parsers rather than hand-coded parsers.

Related Topic