Click here to Skip to main content
15,881,826 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have managed to solve the problem in converting infix to postfix (using stack) but
it can only handle one digit at a time. so it means i am using character to scan it
from left to right.

Please help me or give me some tricks on how i can make my code handle two digits or more.
Example:

This has only one digit every operand
input infix is : 2+3*6/7

This has two or more digit every operand.
input infix is : 23+345*6/32

In my code:
I convert the input string into an array of characters
input.toCharArray();
and scan the the array from left to right.

string input = txtInput.Text;
char[] toArray = new char[input.Length];
toArray = input.ToCharArray();

Creating method to evaluate each character[Example code]:

public void Evaluate(char[] array)
{

for (int i = 0; i < array.Length; i++)
{

char current = array[i];
switch (current)
{
case '+':
case '-':
Process(1, current);
break;
case '*':
case '/':
Process(2, current);
break;
case '(':
st.Push(current);
break;
case ')':
while (!this.isEmpty())
{
char pop =(char) st.Pop();
if (pop == '(')

break;
else
postString += pop;
}
break;
default:
if (char.IsLetterOrDigit(current))
{
postString += current.ToString();
}
break;
}

}
try
{
while (!this.isEmpty())
{
char pop = (char)st.Pop();
MessageBox.Show("Popped left: " + pop);
postString += pop;
}
}
catch
{
}



==========================Thank You==================================
Posted
Comments
BillWoodruff 13-Aug-11 1:28am    
Hi, What's your goal here: do you just want to find the right code to implement, or do you want to write your own lexer/parser in order to develop your coding skills ? Are you willing to go and study algorithms for parsing ? Or, would using a tool like Bison to generate a parser/lexer work for you ?

If you want to handle translating infix's operator-precedence and nested parentheses: that requires a recursive descent parser: http://en.wikipedia.org/wiki/Recursive_descent_parser ... do you want to learn how to write one ?

Example: infix 5 + 11 * 5 = 60 because * has greater precedence than +, so to write that out in postfix, you need to translate to:

5 11 * 5 +

1 solution

If you are going to do it from a character array and can assume integer values, then when you get a numeric value, you will need to accumulate the number, but you won't generally be able to store that in a char variable.

There are generalized parsers available (use Google), but if I were going to write one, I would not start with a character array, but parse "tokens" that would be math symbols, keywords, numbers, variable names, etc.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900