I code this in C, it's for infix to postfix translation, but It doesn't work and I can't understand why, I changed it many times...
The input should be a (supposed correct) expression between parenthesis in infix notation, the usual way we write with * and / having precedence on + and -, and the parenthesis giving precedence. The postfix notation doesn't have parenthesis, for example: If I put an input expression like((8-9)/6) the expected output is 8 9 - 6 /
The program starts, but the output is really wrong, for example: input: ((8-9)+7) output: 8-97 expected output: 8 9 7 - + input: ((6+9)/7) output: 6+++++97 expected output: 6 9 + 7 /
here how I planned to do it: 1) If an operand is encountered, output it. 2) If a ( is encountered push it onto the Stack. 3) If an operator is encountered, then Repeatedly pop from stack and output each operator which has same precedence as or higher precedence than the operator encountered. Push the operator on the stack. 4) If a ) is encountered, then Repeatedly pop from the stack and output each operator until a left parenthesis is encountered. Remove the ) parenthesis.
#include <stdio.h>
#include <stdlib.h>
#define N 100
char ch;
struct stack {
char exp[N];
int index;
} stack;
void push (char ch) {
stack.exp[stack.index] = ch;
stack.index++;
}
char pop () {
stack.index--;
return stack.exp[stack.index];
}
int pr_op(char ch) {
if (ch == '+' || ch == '-')
return 0;
else if (ch == '*' || ch == '/')
return 1;
}
char translator(char ch) {
int i;
if (ch == '(')
{
push(ch);
}
else if (ch == ')')
{
i = stack.index;
while(stack.exp[--i] != '\0' && stack.exp[--i] != '(')
{
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
putchar(ch);
}
else
{
pop();
}
}
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
i= stack.index;
while(stack.exp[--i] != '\0' && pr_op(stack.exp[i])>=pr_op(ch))
{
putchar(ch);
}
push(ch);
}
else //operand
{
putchar(ch);
}
}
main(int argc, char *argv[])
{
ch = getchar();
stack.index = 0;
while ( ch != '\0'){
stack.exp[stack.index]=ch;
translator(ch);
stack.index++;
ch = getchar();
}
printf("\n");
return 0;
}