neco

neco

  • NA
  • 1
  • 0

Postfix to Infix and showing steps to user

Jun 2 2010 12:05 PM
Hello. I have to write a code where the user writes in postfix and the program transforms to infix. But that is not the problem, the problem is that in every step of this transformation I have to show in console app every step of this transformation, so I'm guessing what went out and what was left in the stack, but I don't know how to do this.  Please any help will be greatly appreciated and I will kiss your feet :D  Sorry for the broken English (Serbian).

 using System;
using System.Collections.Generic;

class Rpn
{
    public
static void Main()
    {
        char[] sp = new char[] { ' ',
'\t' };
        for (;; )
        {
            string s =
Console.ReadLine();
            if (s == null) break;
            Stack<string>
tks = new Stack<string>
                 (s.Split(sp,
StringSplitOptions.RemoveEmpty
Entries));
            if
(tks.Count == 0) continue;
            try
            {
                double
r = evalrpn(tks);
                if (tks.Count != 0) throw new
Exception();
                Console.WriteLine(r);
            }
            catch
(Exception e) { Console.WriteLine("error"); }
        }
    }

    private
static double evalrpn(Stack<string> tks)
    {
        string
tk = tks.Pop();
        Console.WriteLine("sklad: " + tk);
        double
x, y;
        if (!Double.TryParse(tk, out x))
        {
            y
= evalrpn(tks); x = evalrpn(tks);
            if (tk == "+")
            {
                Console.WriteLine(x
+ " " + y);
                x += y;
            }
            else
if (tk == "-")
            {
                Console.WriteLine(x +
" " + y);
                x -= y;
            }
            else
if (tk == "*")
            {
                Console.WriteLine(x +
" " + y);
                x *= y;
            }
            else
if (tk == "/")
            {
                Console.WriteLine(x +
" " + y);
                x /= y;
            }
            else
throw new Exception();
        }
        return x;
    }
}