Parsing mathematical experssions with two values that have parenthesis and minus signs

Posted by user45921 on Programmers See other posts from Programmers or by user45921
Published on 2014-06-08T21:55:22Z Indexed on 2014/06/09 3:41 UTC
Read the original article Hit count: 273

Filed under:
|

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

100+100

-100-100

-(100)+(-100)

sqrt(100)

by the minues signs, parenthesis 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 have I written for the other basic operations without parenthesis and the minus sign for the second value and it works great for the simple ones. I'm using a switch method to calculate the add, sub, mul and divide 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 using a function like strtok to properly parse the parenthesis and the minus signs. Any kind help?

© Programmers or respective owner

Related posts about c

    Related posts about parsing