LibMeval: Math, Strings, and C

I have run into multiple situation while programming in C where I found I needed to take in a string that would contain a math expression like “2+2” and evaluate it.  After googling, I could only find C++ libraries, and I finally got fed up with it and wrote a library that will do this automatically.  It is a very simple library and very small (about 15Kb), and does handles addition, subtraction, multiplication, division, and parentheses.

It has one function at the moment that is of use: eval(). Here is its prototype:

int eval(char* str, double *ret);

str is the expression and ret is a pointer to a double where the result will be stored. It returns 1 if there is no syntax error in the expression or 0 if there is.

Here is a quick little sample that I used to test and debug the library:

int main()
    char *c = malloc(256);

    while (1)
    double result;
    fgets(c, 256, stdin);
    if (eval(c, &result))
        printf("ANSWER IS: %f\n", result);
        puts("syntax error");


    return 0;

I am still working out a kink or two, but it is in working order. You may get the code by running:
darcs get http://patch-tag.com/r/jimi_hendrix/libmeval/pullrepo libmeval

Check out the README for more details.


0 Responses to “LibMeval: Math, Strings, and C”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Recent Comments


%d bloggers like this: