0

Possible Duplicate:
What is a fast C or Objective-C math parser?

What function code could I use to convert a dynamic string into an expression and evaluate it ?

#include <stdio.h>
#include <conio.h>
#include <string.h>
int main() {
  char var1[] = "3";
  char var2[] = "2";
  char var3[] = "5";
  char exp[20]  = "";
  int result;

  // Trying to create a random expression "(3+2)*5" 
  strcat(exp, "( ");
  strcat(exp, var1);
  strcat(exp, " + ");  
  strcat(exp, var2);  
  strcat(exp, " ) * ");  
  strcat(exp, var3);    

  result = somefunction(exp);

  printf("Result : %i\n", result);
  return 0;
}
Community
  • 1
  • 1
Me Unagi
  • 405
  • 1
  • 8
  • 17

2 Answers2

3

You have to parse the string and evaluate it - it's far from trivial, sorry. But you can see a working example here.

0

You're talking about writing a parser. Your first step is to figure out your rules for that parser.

If you define them simply "all math is evaluated left to right, parens take priority", then it's not terrifically difficult. But that obviously produces some unexpected results for "1+2*3".

If you have the option, a reverse-polish-notation calculator is much easier to implement. If you don't have that option, you will probably need to parse into a tree to start, then evaluate in "leaf-to-root" order.

jkerian
  • 16,497
  • 3
  • 46
  • 59
  • Well... I remember it was my school homework a long time ago for me.. :) Just to add to what jkerian said. There is no "function" to evaluate such an expression. You'll have to write it yourself which happens to be a parser... – Ya. Dec 13 '12 at 20:07