I was trying to write a code to convert infix expression into postfix expression , I have the source code here and when I compile and give the input say 'a+b' it returns 'ab?' as the answer it does not show the operator symbols at all. Can you guys please tell me where I have gone wrong.!!
It also shows this warning when I compile
infpos.c:74:1: warning: non-void function does not return a value in all control paths [-Wreturn-type]
PS: I got to know what is the error.. Thank you
(The error was in the line 58 I had to use prefix increment but I had used postfix increment)
#include<stdio.h>
#include<ctype.h>
#define max 30
void main()
{
char inf[30],post[30];
void convert(char [],char []);
printf("Enter the infix exxpression\n");
scanf("%s",inf);
convert(inf,post);
printf("Postfix expression is\n");
printf("%s\n",post);
}
void convert(char inf[],char post[])
{
int i,j=0,top=-1,f=1,test;
char stack[30],ch,x;
int check(char);
int pre(char);
for(i=0;inf[i]!='\0';i++)
{
ch = inf[i];
test = check(ch);
switch(test)
{
case 1:
post[j++] = ch;
break;
case 2:
stack[++top] = ch;
break;
case 3:
while((x=stack[top--])!='(')
post[j++] = x;
break;
case 4:
do
{
if(top==-1)
f = 1;
else if(stack[top] == '(')
f = 1;
else if(pre(ch)>pre(stack[top]))
f = 1;
else
{
post[j++] = stack[top--];
f = 0;
}
}while(f==0);
stack[top++] = ch;
break;
}
}
while(top!=-1)
post[j++] = stack[top--];
post[j] = '\0';
}
int pre(char op)
{
if(op == '+' || op=='-')
return 1;
else if(op == '/' || op=='*' || op =='%')
return 2;
else if(op=='^')
return 3;
}
int check(char ch)
{
if(isalnum(ch))
return 1;
else if(ch=='(')
return 2;
else if(ch == ')')
return 3;
else if(ch == '+' || ch =='-' || ch=='/' || ch =='*' || ch=='%' || ch=='^')
return 4;
else
return 5;
}
Related
I've written a C code to check for simple parenthesis balancing which prints NO and YES if balanced, not balanced respectively.
The problem is that I'm getting NO for all inputs. Hence I'm thinking that its a semantic error but cannot find it (I have been trying for 2 days :p)
Could someone please help me here? thanks!
#include <stdio.h>
#include <stdlib.h>
typedef struct stack {
char s[1000];
int top;
} STACK;
void create(STACK *sptr) {
sptr->top = -1;
}
int isEmpty(STACK *sptr) {
if (sptr->top == -1)
return 1;
else
return 0;
}
void push(STACK *sptr, char data) {
sptr->s[++sptr->top] = data;
}
char pop(STACK *sptr) {
if (isEmpty(sptr) == 0)
return sptr->s[sptr -> top];
else
return '$';
}
char *isBalanced(char *s, STACK *sptr) {
char *y, *n;
int i = 0;
y = (char*)malloc(sizeof(char) * 4);
y[0] = 'Y';
y[1] = 'E';
y[2] = 'S';
y[3] = '\0';
n = (char*)malloc(sizeof(char) * 3);
n[0] = 'N';
n[1] = 'O';
n[2] = '\0';
while (s[i] != '\0') {
if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
push(sptr, s[i]);
} else {
char x = pop(sptr);
switch (s[i]) {
case ')':
if (x != '(')
return n;
break;
case '}':
if (x != '{')
return n;
break;
case ']':
if (x != '[')
return n;
break;
}
}
++i;
}
if (isEmpty(sptr))
return y;
else
return n;
}
int main() {
STACK *sptr = (STACK *)malloc(sizeof(STACK));
char c[21];
int ch;
do {
printf("enter sequence:");
scanf("%s", c);
char *msg = isBalanced(c, sptr);
printf("%s", msg);
printf("choice?:");
scanf("%d", &ch);
} while(ch);
}
updated code:
#include <stdio.h>
#include <stdlib.h>
typedef struct stack {
char s[1000];
int top;
} STACK;
void create(STACK *sptr) {
sptr->top = -1;
}
int isEmpty(STACK *sptr) {
if (sptr->top == -1)
return 1;
else
return 0;
}
void push(STACK *sptr, char data) {
sptr->s[++sptr->top] = data;
}
char pop(STACK *sptr) {
if (isEmpty(sptr) == 0)
return sptr->s[sptr->top--];
else
return '$';
}
int isBalanced(char *s, STACK *sptr) {
int i = 0;
while (s[i] != '\0') {
if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
push(sptr, s[i]);
} else {
char x = pop(sptr);
switch (s[i]) {
case ')':
if (x != '(')
return 0;
break;
case '}':
if (x != '{')
return 0;
break;
case ']':
if (x != '[')
return 0;
break;
}
}
++i;
}
if (isEmpty(sptr))
return 1;
else
return 0;
}
int main() {
STACK *sptr = malloc(sizeof(STACK));
char c[21];
int ch;
do {
printf("enter sequence:");
scanf("%s", c);
printf("%s", (isBalanced(c, sptr) ? "YES" : "NO"));
printf("choice?:");
scanf("%d", &ch);
} while(ch);
}
Here are some major issues in your code:
you do not properly initialize the stack with create(sptr) before use, preferably in main() where it is defined. Your code has undefined behavior. It prints NO by chance, probably because sptr->top has an initial value of 0, which makes the stack non-empty.
you should only pop from the stack when you encounter a closing delimiter ), ] or }.
you should prevent potential buffer overflow by telling scanf() the maximum number of characters to read into c: scanf("%20s", c). Furthermore you should test the return value to avoid undefined behavior at end of file.
Note also that the STACK can be made a local variable to avoid heap allocation and potential allocation failure, which would cause undefined behavior since it is not tested.
Here is a corrected version:
#include <stdio.h>
typedef struct stack {
char s[1000];
int top;
} STACK;
void create(STACK *sptr) {
sptr->top = -1;
}
int isEmpty(STACK *sptr) {
if (sptr->top == -1)
return 1;
else
return 0;
}
void push(STACK *sptr, char data) {
sptr->s[++sptr->top] = data;
}
char pop(STACK *sptr) {
if (isEmpty(sptr) == 0)
return sptr->s[sptr->top--];
else
return '$';
}
int isBalanced(char *s, STACK *sptr) {
int i;
for (i = 0; s[i] != '\0'; i++) {
switch (s[i]) {
case '(':
case '{':
case '[':
push(sptr, s[i]);
break;
case ')':
if (pop(sptr) != '(')
return 0;
break;
case '}':
if (pop(sptr) != '{')
return 0;
break;
case ']':
if (pop(sptr) != '[')
return 0;
break;
}
}
return isEmpty(sptr);
}
int main() {
STACK s, *sptr = &s;
char c[100];
int ch;
do {
printf("Enter sequence: ");
if (scanf(" %99[^\n]", c) != 1)
break;
create(sptr);
printf("%s\n", isBalanced(c, sptr) ? "YES" : "NO");
printf("Choice? ");
if (scanf("%d", &ch) != 1)
break;
} while (ch);
return 0;
}
In your pop function you are not decrementing the top thus your isEmpty function always returns false.
Hence you return no always.
char* isBalanced(char* s, STACK* sptr)
{
....
if(isEmpty(sptr)) return y;
else return n;
}
The following is the correct implementation:
char pop(STACK* sptr)
{
if(isEmpty(sptr) == 0)
return sptr->s[sptr->top--];
else
return '$';
}
I assume that the idea is this: an opening paren is always permitted (in the analyzed text), but a closing paren must match the last opened. This is why a stack is required. Also, in the end, if the stack is not empty that means that some parens were not closed.
So, you should use the stack, but only when you encounter parens - either opening or closing.
In the function isBalanced(), the main cycle could be this:
while (s[i] != '\0') {
if ( s[i] == '(' || s[i] == '{' || s[i] == '[' ) {
// opening - remember it
push(sptr, s[i]);
} else if ( s[i] == ')' || s[i] == '}' || s[i] == ']' ) {
// closing - it should match
if ( ! popmatch(sptr, s[i]) )
return n;
}
++i;
}
The rest of the function is ok. Now, I modified the the pop() function: renamed to popmatch, because it should check if the argument matches the top of the stack. If it does, pop the stack and return OK. So the function would be:
char popmatch(STACK* sptr, char c) {
// an empty stack can not match
if (isEmpty(sptr))
return 0;
// not empty, can check for equality
if ( c =! sptr->s[sptr->top] )
return 0;
// does not match!
// ok, it matches so pop it and return ok
sptr->top--;
return 1;
}
Please note that the code mirrors pretty well the "analysis"; when the analysis is short and clear, and the code follows the analysis, the result often is short and clear too.
I would add the flags to see which one does not match
unsigned match(const char *f)
{
int p = 0,s = 0,b = 0;
while(*f)
{
switch(*f++)
{
case '(':
p++;
break;
case ')':
p -= !!p;
break;
case '[':
s++;
break;
case ']':
s -= !!s;
break;
case '{':
b++;
break;
case '}':
b -= !!b;
break;
default:
break;
}
}
return (!p) | ((!s) << 1) | ((!b) << 2);
}
Not the stack version but just for the idea. It is rather easy to add push and pop
What does it mean by item=infix_exp[i++]; in the following C code? Line no 21. It is for infix to postfix conversion. As far as I know, here i is array index. But why is it incrementing without any loop?
This is the Code
#include<stdio.h>
#include<conio.h>
#define SIZE 100
int top = -1;
char stack[SIZE];
void push(char item);
char pop();
int is_operator(char symbol);
int precedence(char symbol);
void main()
{
int i;
int j;
char infix_exp[SIZE], postfix_exp[SIZE];
char item;
char x;
printf("\nEnter Infix expression in parentheses: \n");
gets(infix_exp);
i=0;
j=0;
item=infix_exp[i++]; /* HERE */
while(item != '\0')
{
if(item == '(')
{
push(item);
}
else if((item >= 'A' && item <= 'Z') ||
(item >= 'a' && item <= 'z'))
{
postfix_exp[j++] = item;
}
else if(is_operator(item) == 1)
{
x=pop();
while(is_operator(x) == 1 && precedence(x)
>= precedence(item))
{
postfix_exp[j++] = x;
x = pop();
}
push(x);
push(item);
}
else if(item == ')')
{
x = pop();
while(x != '(')
{
postfix_exp[j++] = x;
x = pop();
}
}
else
{
printf("\nInvalid Arithmetic Expression.\n");
getch();
}
item = infix_exp[i++];
}
postfix_exp[j++] = '\0';
printf("\nArithmetic expression in Postfix notation: ");
puts(postfix_exp);
getch();
}
void push(char item)
{
if(top >= SIZE-1)
{
printf("\nStack Overflow. Push not possible.\n");
}
else
{
top = top+1;
stack[top] = item;
}
}
char pop()
{
char item = NULL;
if(top <= -1)
{
printf("\nStack Underflow. Pop not possible.\n");
}
else
{
item = stack[top];
stack[top] = NULL;
top = top-1;
}
return(item);
}
int is_operator(char symbol)
{
if(symbol == '^' || symbol == '*' || symbol == '/' ||
symbol == '+' || symbol == '-')
{
return 1;
}
else
{
return 0;
}
}
int precedence(char symbol)
{
if(symbol == '^')
{
return(3);
}
else if(symbol == '*' || symbol == '/')
{
return(2);
}
else if(symbol == '+' || symbol == '-')
{
return(1);
}
else
{
return(0);
}
}
item=infix_exp[i++]; means to fetch ith element of the array to item, then increment i by 1.
It seems the line is there because the author of the code prefered to write item=infix_exp[i++]; twice (the another one is in line 59) to using while((item=infix_exp[i++]) != '\0').
item=infix_exp[i++]; is equivalent to
item=infix_exp[i];
i++;
except that latter has one more sequence point.
It is just the same as
item=infix_exp[i];
i = i + 1;
The statement where you are getting confused is
item=infix_exp[i++]
Before this line of statement if the value of i is 0 then in this line the value of i is also 0 but the value of i in the next line is 1.
This statement is not in loop but the value of i is used in a loop. Each time the loop iterates the value of i is increased by one. Besides, i++ has no relation with loop. If you want to make the effect of increment in the very next line then you can do so.
I've searched the site to see if there are any similar questions to mine, but I can't seem to find one which offers a working solution. Below is the code to a fully functional infix to postfix converter for arithmetic syntax.
The issue is that if the user enters a string such as 23+89, the infix output is 2389+. This is of course correct, however I wish to add separators between the operands to distinguish between 23 and 89. How can this be implemented with the array I am using? Do I need to add a whitespace character between the operands in the array? How can this be achieved?
Any insight will be greatly appreciated.
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#define MAX 100 // maximum number of input characters
int precedence(char x);
struct stack
{
char my_stack[MAX];
int pointer;
};
int precedence(char x)
{
if(x == '(')
return(0);
if(x == '+' || x == '-')
return(1);
if(x == '*' || x == '/')
return(2);
return(3);
}
int main(void)
{
struct stack S;
S.pointer = 0;
char c;
char output[MAX]; // stores output
int out_count = 0; // stores no. of characters of output
char data; // stores data being popped off the stack
printf("Enter an expression to check:\n");
fflush(stdout);
while(('\n' != (c=getchar())))
{
if(isdigit(c)) // if an operand is found print to screen
{
output[out_count] = c;
out_count++;
}
else if(c == '(') // if ( is found push on stack
{
S.pointer = S.pointer +1;
S.my_stack[S.pointer] = c;
}
else if(c == ')') // if ) is found pop stack until ( is found
{
while(!(S.my_stack[S.pointer] == '('))
{
data = S.my_stack[S.pointer];
output[out_count] = data;
out_count++;
S.pointer = S.pointer -1;
}
S.pointer = S.pointer -1; // pop the extra (
}
else if(c == '*' || c == '/' || c == '+' || c == '-')
{
if((S.pointer) == 0)
{
S.pointer = S.pointer +1;
S.my_stack[S.pointer] = c;
}
else
{
if(precedence(S.my_stack[S.pointer]) > precedence(c))
{
// pop stack
int i;
for(i=(S.pointer); i >= 0; i--)
{
if(c == '(' || c == ')')
continue;
output[out_count] = c;
out_count++;
}
S.pointer = 0;
}
else
{
// push c on stack
S.pointer = S.pointer +1;
S.my_stack[S.pointer] = c;
}
}
}
}
int j = S.pointer;
while(j != 0)
{
if(S.my_stack[j] == '(')
continue;
output[out_count] = S.my_stack[j];
out_count++;
j--;
}
output[out_count+1] = '\0';
int k=0;
while(output[k] != '\0') // go through output array and print
{
printf("%c", output[k]);
k++;
}
return 0;
}
23+89, the infix output is 2389+. This is of course correct,
Well, no. 2389 is not the same as 23 and 89.
You could either add whitespace, or an explicit "push" operator. HP calculators often use an up arrow ↑ symbol to show that operation.
I am trying to solve one problem from spoj http://www.spoj.com/problems/ARITH2/
But every time i am getting 'WA' Wrong Answer.I've tried every possible Test Case and it's giving me expected results.I've written the code mentioned below:
#include <stdio.h>
int main() {
int t,s=0;char operator;
scanf("%d",&t);
while(t--)
{
signed long long int s=0,c=0;
scanf("%lld",&s);
while(1)
{
operator=0;
operator=getc(stdin);
if(operator=='=')
break;
scanf("%lld",&c);
switch(operator)
{
case '+' : s=s+c;
break;
case '-' : s=s-c;
break;
case '*' : s=s*c;
break;
case '/' : s=s/c;
break;
}
}
printf("%lld\n",s);
}
return 0;
}
Please check the requirement, you should not use scanf instead, using sscanf cos the input is whole expression such 50 * 40 * 250 + 791 =. You can create a simple parser as below code to walkthrough whole expression.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char ch = 0;
int state = 0;
char buff[128];
char ops = 0;
unsigned int result = 0;
int i = 0, idx = 0;
char expr[1024];
int cnt = 0;
if (scanf("%[^=]=%n", expr, &cnt) <= 0)
return 0;
while(idx < cnt) {
ch = expr[idx++];
printf("state %d ch %c\n", state, ch);
switch(state) {
case 0:
if ((ch <= '9') && (ch >= '0')) {
state++;
buff[i++] = ch;
}
break;
case 1:
if ((ch <= '9') && (ch >= '0')) {
buff[i++] = ch;
} else {
buff[i] = '\0';
if (i > 0) {
unsigned int num = atoi(buff);
switch (ops) {
case '-':
result -= num;
break;
case '+':
result += num;
break;
case '*':
result *= num;
break;
case '/':
result /= num;
break;
default:
result = num;
break;
}
printf("> found fact %d, result %u\n", num, result);
}
i = 0;
if ((ch == '-') || (ch == '+') || (ch == '*') || (ch == '/')) {
state = 0;
ops = ch;
printf("> found ops %c\n", ch);
} else if ((ch == ' ') || (ch == '\t')) {
continue;
} else if (ch == '=') {
break;
} else {
// expression end
break;
}
}
break;
default:
break;
}
}
printf("> result '%u' ", result);
return 0;
}
Quick glance, it doesn't look like you are respecting the spacing outlined in the spec. For example, 1 + 1 * 2 = is going to read the wrong character for operator. 1+1*2= looks like it'll work, but that's not what was asked for.
Also, you're reading in unsigned integers and will instantly fail any test cases with signed numbers.
I'm solve an exercise in which one of the functions has to translate infix notation to postfix notation. Here follows my whole code
#include<stdio.h>
#define MAX 100
char stack[MAX];
int top;
void compact(char Descomp[], char Compac[]);
void init_stack();
int push(char Elem);
int desempilha(char *Elem);
int priority(char Operator);
int arity(char Exp[], int position);
int translate_pos(char exp[], char exp_pos[]);
int main()
{
char Exp[MAX]; /* stores the expression read from stdin */
char Exp_compact[MAX]; /* stores expression without spaces */
char Exp_pos[MAX]; /* stores the expression after the translation for postfix*/
int indicator; /* indicate if an error occurred, 0 for NO ERROR and -1 for ERROR*/
indicator = 0;
printf("\nType the expression: ");
gets(Exp);
compact(Exp, Exp_compact);
indicator = translate_pos(Exp_compact, Exp_pos);
puts(Exp_pos);
return indicator;
}
/* compact function delete spaces within the expression read from stdin */
void compact(char Descomp[], char Compac[])
{
int i;
int j;
i = 0;
j = 0;
while(Descomp[j] != '\0')
{
if(Descomp[j] != ' ')
{
Compac[i] = Descomp[j];
i++;
}
j++;
}
}
/* initiate the stack by setting top = -1 */
void init_stack()
{
top = -1;
}
/* puts the element Elem in the stack */
int push(char Elem)
{
if(top == MAX - 1) /* Stack is full */
return -1;
top++;
stack[top] = Elem;
return 0;
}
/* remove the element in stack[top] and puts it in &Elem*/
int pop(char *Elem)
{
if(top == -1) /* stack is empty */
return -1;
*Elem = stack[top];
top--;
return 0;
}
/* Return the priority of an operator */
int priority(char Operator)
{
switch(Operator)
{
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
case '^': return 3;
case '(': return 4;
case ')': return 5;
default : return 0;
}
}
/* returns the arity of CONSTANTS + - * / and ^, for ( an ) is merely symbolic */
int arity(char Exp[], int position)
{
if(priority(Exp[position]) == 1)
{
if( (position == 0) || ( (priority(Exp[position - 1]) >= 1) && (priority(Exp[position - 1]) <= 3) ))
return 1;
else
return 2;
}
else if( (priority(Exp[position]) > 1) && (priority(Exp[position]) <= 4))
return 2;
else
return priority(Exp[position]);
}
/* reads an infix expression and returns postfix expression */
int translate_pos(char exp[], char exp_pos[])
{
int i;
int j;
int ind;
char trash;
i = 0;
j = 0;
ind = 0;
trash = ' ';
init_stack();
while(exp[i]!= '\0')
{
if(arity(exp, i) == 0)
{
exp_pos[j] = exp[i];
j++;
}
if(arity(exp, i) == 1)
{
switch(exp[i])
{
case '-':
{
exp_pos[j] = exp_pos[i];
j++;
}
case '+': trash = exp_pos[i];
}
}
if(arity(exp, i) == 2)
{
while((top != -1) && (priority(stack[top]) <= priority(exp[i])))
{
ind = pop(&exp_pos[j]);
j++;
}
ind = push(exp[i]);
}
if(priority(exp[i]) == 4)
{
ind = push(exp[i]);
}
if(priority(exp[i]) == 5)
{
while( (top != -1) && (stack[top] != '('))
{
ind = pop(&exp_pos[j]);
j++;
}
if(stack[top] == '(')
ind = pop(&trash);
}
i++;
}
while(top != -1)
{
ind = pop(&exp_pos[j]);
j++;
}
return ind;
}
The algorithm I used to translate the expression is
while there is token to be read;
read the token;
if token is a constant
push it to Exp_Postfix;
if token is '('
push it to stack
if token is ')'
pop from the stack all symbols until '(' be find and remove '(' from the stack
if token is an operator and its arity is 2
pop all operators with less or equal priority than the token and store then in the Exp_Postfix;
push token to the stack;
if token is an operator and its arity is 1
if token is '-'
push it to Exp_postfix;
if token is '+'
pass to the next token;
pop all remaining symbols in the stack and push then, in order, to the Exp_Postfix;
I compiled the .c archive using
gcc -Wall archive.c -o archive
and executed it. I give the expression
5+(6*9^14)
It the returned expression was
5
I do not now if the error is in my code or in solution to the problem.
There are an awful lot of problems, here, for instance:
compact() and translate_pos() leave Exp_compact and Exp_pos, respectively, without a terminating \0, so you're getting garbage printed out.
your arity() function is returning 2 for an opening parenthesis.
in the first switch statement of translate_pos(), you're missing break statements.
Your priority comparison in translate_pos() when arity is 2 is back to front.
When you're comparing operator precedence, you should treat an opening parenthesis specially, since it should have the lowest precedence when on the top of the stack.
You should have a lot more else keywords in translate_pos().
You're using gets(), which was always bad, and now has actually been removed from C.
I haven't exhaustively tested it, but here's a correct version that seems to work for all the test inputs I tried:
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
/* Function prototypes */
void compact(char Descomp[], char Compac[]);
void init_stack();
int push(char Elem);
int desempilha(char *Elem);
int priority(char Operator);
int arity(char Exp[], int position);
int translate_pos(char exp[], char exp_pos[]);
/* Stack variables */
#define MAX 100
char stack[MAX];
int top;
int main(void) {
char Exp[MAX];
char Exp_compact[MAX] = {0};
char Exp_pos[MAX] = {0};
int indicator = 0;
printf("\nType the expression: ");
fgets(Exp, MAX, stdin);
compact(Exp, Exp_compact);
indicator = translate_pos(Exp_compact, Exp_pos);
puts(Exp_pos);
return indicator;
}
/* compact function delete spaces within the expression read from stdin */
void compact(char Descomp[], char Compac[]) {
int i = 0;
int j = 0;
while ( Descomp[j] ) {
if ( !isspace(Descomp[j]) ) {
Compac[i++] = Descomp[j];
}
j++;
}
}
/* initiate the stack by setting top = -1 */
void init_stack() {
top = -1;
}
/* puts the element Elem in the stack */
int push(char Elem) {
if (top == MAX - 1) /* Stack is full */
return -1;
stack[++top] = Elem;
return 0;
}
/* remove the element in stack[top] and puts it in &Elem*/
int pop(char *Elem) {
if (top == -1) /* stack is empty */
return -1;
*Elem = stack[top--];
return 0;
}
/* Return the priority of an operator */
int priority(char Operator) {
switch (Operator) {
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '^':
return 3;
case '(':
return 4;
case ')':
return 5;
default:
return 0;
}
}
/* returns the arity of OPERATORS + - * / and ^,
* for ( an ) is merely symbolic */
int arity(char Exp[], int position) {
if ( priority(Exp[position]) == 1 ) {
if ( (position == 0) ||
((priority(Exp[position - 1]) >= 1) &&
(priority(Exp[position - 1]) <= 3)) ) {
return 1;
} else {
return 2;
}
} else if ( (priority(Exp[position]) > 1) &&
(priority(Exp[position]) <= 3) ) {
return 2;
} else {
return priority(Exp[position]);
}
}
/* reads an infix expression and returns postfix expression */
int translate_pos(char exp[], char exp_pos[]) {
int i = 0, j = 0, ind = 0;
char trash = ' ';
init_stack();
while ( exp[i] ) {
if ( arity(exp, i) == 0 ) {
exp_pos[j++] = exp[i];
} else if ( arity(exp, i) == 1 ) {
switch (exp[i]) {
case '-':
exp_pos[j++] = exp[i];
break;
case '+':
trash = exp_pos[i];
break;
default:
assert(0);
}
} else if (arity(exp, i) == 2) {
while ( (top != -1) &&
(priority(stack[top]) >= priority(exp[i])) &&
stack[top] != '(' ) {
ind = pop(&exp_pos[j++]);
}
ind = push(exp[i]);
} else if ( priority(exp[i]) == 4 ) {
ind = push(exp[i]);
} else if ( priority(exp[i]) == 5 ) {
while ( (top != -1) && (stack[top] != '(') ) {
ind = pop(&exp_pos[j++]);
}
if ( (top != - 1) && stack[top] == '(') {
ind = pop(&trash);
}
}
i++;
}
while (top != -1) {
ind = pop(&exp_pos[j++]);
}
return ind;
}
Gives the following output for various test cases:
paul#local:~/src/c/postfix$ ./postfix
Type the expression: 1+2
12+
paul#local:~/src/c/postfix$ ./postfix
Type the expression: (1+2)
12+
paul#local:~/src/c/postfix$ ./postfix
Type the expression: 1+2*3
123*+
paul#local:~/src/c/postfix$ ./postfix
Type the expression: (1+2)*3
12+3*
paul#local:~/src/c/postfix$ ./postfix
Type the expression: (3+4)*4/2
34+4*2/
paul#local:~/src/c/postfix$ ./postfix
Type the expression: 5+(6*9^14)
56914^*+
paul#local:~/src/c/postfix$
I'd suggest comparing my code to yours and trying to understand the individual differences to see where you were going wrong.