Ali Aryan
Ali Aryan

Reputation: 31

I need help to convert from infix to postfix in C

I was practising some data structures problems that I did previously but this time I don't know what is going wrong in my code. I looked over a long time but I did not found the mistake. When I'm printing I'm just getting the first character and it looks like e is not being updated. But I've written e++.

#include<stdio.h>
#include "ctype.h"
int stack[20];
int top = -1;

void push(int x)
{
    stack[++top] = x;
}

int pop()
{
    return stack[top--];
}
int priorityof(char x)
{
    if(x=='(')
        return 3;
    else if(x=='+'|| x=='-')
        return 1;
    else if(x=='*'|| x=='/')
        return 2;
}

int main()
{
    char exp[20];
    char *e;
    e=exp;char x;
    scanf("%c",exp);
    while(*e!='\0')
    {
        if(isalnum(*e))
        {
            printf("%c", *e);
        }
        else if(*e=='(')
        {
            push(*e);
        }
        else if(*e==')')
        {
            while((x=pop())!='(')
                printf("%c",x);
        }
        else {
            while (priorityof(stack[top]) >= priorityof(*e)) {
                printf("%c", pop());
                push(*e);
            }

        }
        e++;
    }
    while(top!=-1)
    {
        printf("%c",pop());
    }
}

Upvotes: 2

Views: 114

Answers (1)

Sandipan
Sandipan

Reputation: 703

%c is for single character and reading your question it seems like you are giving more than one character so its a string, use %s.


#include<stdio.h>
 #include "ctype.h" 
int stack[20]; int top = -1;
 void push(int x) { 
stack[++top] = x;
 } 
int pop() { return stack[top--]; } 
int priorityof(char x) {
 if(x=='(') return 3;
 else if(x=='+'|| x=='-') return 1;
 else if(x=='*'|| x=='/') return 2;
 } 
int main() { 
char exp[20]; 
char *e; 
e=exp;char x; 
scanf("%s",exp); 
while(*e!='\0') { if(isalnum(*e)) { printf("%c", *e); } else if(*e=='(') { push(*e); } else if(*e==')') { while((x=pop())!='(') printf("%c",x); } else { while (priorityof(stack[top]) >= priorityof(*e)) { printf("%c", pop()); push(*e); } } e++; } while(top!=-1) { printf("%c",pop()); } }

Upvotes: 1

Related Questions