This morning I've written a simple
Infix Notation Evaluator in C, and this afternoon I've rewritten it in C#. I Think that C# is more easy to understand than C, so I've posted the C# Example. (If you want the C example, ask me).
In few words, I take the Input in "Infix Notation" and I convert it in
Reverse Polish Notation (RPN), and then the RPN string is evaluated.
First Example: Evaluating a simple Math Expression.
string expr = "10 + 5 - (2 + (3 * 4) + (5 * 3)) - 4 ^ 2 << 8";
Operation operation = new MyTokener().Parser(expr);
Console.WriteLine("{0} = {1}", expr, operation.Evaluate());
Second Example: Evaluating a simple Math Expression with variables.
Dictionary vars = new Dictionary();
vars.Add("A", "1"); vars.Add("B", "2");
vars.Add("C", "3"); vars.Add("D", "4");
vars.Add("K", "5"); vars.Add("L", "6");
string expr = "(A + B) + C + (D * (K + (L - 1)))";
Operation operation = new MyTokener().Parser(expr);
Console.WriteLine("{0} = {1}", expr, operation.Evaluate());
Third example: Evaluating simple String expression.
string expr = "'Hello' + ' ' * 3 + \"World\"";
Operation operation = new MyTokener().Parser(expr);
Console.WriteLine("{0} = {1}", expr, operation.Evaluate());
After the Example you can find the
Source Code Here (You can compile it under Linux with gmcs).
That's all folks! I'm really busy with the Real Work, I'm waiting the 25th for taking a break.