Want to convert infix to postfix in C but getting error empty stack


I write a C code to convert infix expression to postfix expression. The expression may include '^' , "+", "-" , "/", "*" and all three types of brackets i.e." ({[ ". The code should first check whether the brackets are balanced or not and then do the conversion. But the code is showing an empty stack at the output.

Here is my sample code

#include "stackar.h"

#include "fatal.h"

#include <stdlib.h>

#define EmptyTOS(-1)
#define MinStackSize(5)

struct StackRecord {
   int Capacity;
   int TopOfStack;
   ElementType * Array;
};

/* START: fig3_48.txt */
int
IsEmpty(Stack S) {
   return S -> TopOfStack == EmptyTOS;
}
/* END */

int
IsFull(Stack S) {
   return S -> TopOfStack == S -> Capacity - 1;
}

/* START: fig3_46.txt */
Stack
CreateStack(int MaxElements) {
   Stack S;

   /* 1*/
   if (MaxElements < MinStackSize)
      /* 2*/
      Error("Stack size is too small");

   /* 3*/
   S = malloc(sizeof(struct StackRecord));
   /* 4*/
   if (S == NULL)
      /* 5*/
      FatalError("Out of space!!!");

   /* 6*/
   S -> Array = malloc(sizeof(ElementType) * MaxElements);
   /* 7*/
   if (S -> Array == NULL)
      /* 8*/
      FatalError("Out of space!!!");
   /* 9*/
   S -> Capacity = MaxElements;
   /*10*/
   MakeEmpty(S);

   /*11*/
   return S;
}
/* END */

/* START: fig3_49.txt */
void
MakeEmpty(Stack S) {
   S -> TopOfStack = EmptyTOS;
}
/* END */

/* START: fig3_47.txt */
void
DisposeStack(Stack S) {
   if (S != NULL) {
      free(S -> Array);
      free(S);
   }
}
/* END */

/* START: fig3_50.txt */
void
Push(ElementType X, Stack S) {
   if (IsFull(S))
      Error("Full stack");
   else
      S -> Array[++S -> TopOfStack] = X;
}
/* END */

/* START: fig3_51.txt */
ElementType
Top(Stack S) {
   if (!IsEmpty(S))
      return S -> Array[S -> TopOfStack];
   Error("Empty stack");
   return 0; /* Return value used to avoid warning */
}
/* END */

/* START: fig3_52.txt */
void
Pop(Stack S) {
   if (IsEmpty(S))
      Error("Empty stack");
   else
      S -> TopOfStack--;
}
/* END */

/* START: fig3_53.txt */
ElementType
TopAndPop(Stack S) {
   if (!IsEmpty(S))
      return S -> Array[S -> TopOfStack--];
   Error("Empty stack");
   return 0; /* Return value used to avoid warning */
}
/* END */

/* MYCODE TO CONVERT INFIX TO POSTFIX STARTS FROM HERE. THE ABOVE FILE IS "stacker.c"*/

#include <stdio.h>

#include<ctype.h>

#include "stackar.h"

int ismatchingpair(char char1, char char2) // check whether the bracket are same or not
{
   if (char1 == '(' && char2 == ')')
      return 1;
   if (char1 == '[' && char2 == ']')
      return 1;
   if (char1 == '{' && char2 == '}')
      return 1;
   else
      return 0;
}
int bracketsBalance(char * str) {
   Stack S;
   S = CreateStack(20);
   int i;
   for (int i = 0; str[i]; ++i) {
      if (str[i] == '(' || str[i] == '{' || str[i] == '[') // if opening bracket, push it in the stack
      {
         Push(str[i], S);
      } else if (str[i] == ')' || str[i] == '}' || str[i] == ']') // if closing bracket, check whether it matches the opening bracket
      {
         if (ismatchingpair(Top(S), str[i])) // if it matches the opening bracket, pop it in the stack
         {
            Pop(S);
         }
      }
   }
   if (IsEmpty(S)) // if stack is empty, return 1
   {
      return 1;
   } else // else return 0
   {
      return 0;
   }
}

int pr(char symbol) {
   /* Function for precedence */

   if (symbol == '^') /* exponent operator, highest precedence*/ {
      return (3);
   } else if (symbol == '*' || symbol == '/') {
      return (2);
   } else if (symbol == '+' || symbol == '-') /* lowest precedence */ {
      return (1);
   } else {
      return (0);
   }
}
int openingbracket(char x) {
   if (x == '(' || x == '{' || x == '[') {
      return 1;
   } else {
      return 0;
   }
}
int closingbracket(char y) {
   if (y == ')' || y == '}' || y == ']') {
      return 1;
   } else {
      return 0;
   }
}
int checkoperator(char z) {
   if (z == '^' || z == '+' || z == '-' || z == '/' || z == '*') {
      return 1;
   } else {
      return 0;
   }
}
int infixToPostfix(char * infix, char * postfix, int str_size) {
   str_size = strlen(infix);
   Stack S;
   S = CreateStack(20);

   char i;
   for (i = 0; i < str_size; i++) {
      if (!(checkoperator(infix[i]) || openingbracket(infix[i]) || closingbracket(infix[i]))) {
         strncat(postfix, & infix[i], 1);
      } else if (openingbracket(infix[i])) {
         Push(infix[i], S);
      } else {
         checkoperator(infix[i]);
         while (pr(Top(S)) >= pr(i)) {
            strcat(postfix, & infix[i]);
            Pop(S);
         }
         Push(i, S);
      }
   }
   while (Top(S) != '#') {
      TopAndPop(S);
      strncat(postfix, & infix[i], 1);
   }
}
main() {
   int roll_no = 5;
   char in [1000] = "[(62.1+9.0)*(84+roll_no)-2]*4)";
   char post[1000];
   if (bracketsBalance( in )) {
      printf("Brackets in %s are balanced\n", in );
      infixToPostfix( & in [0], & post[0], 1);
      printf("Postfix expressionof %s is: %s\n", in , & post[0]);
   } else {
      printf("Brackets unbalanced. No conversion performed");
   }
   return 0;
}

Asked by:- MehreenSaleem
0
: 2060 At:- 5/17/2021 5:31:12 PM
c c# c++







1 Answers
profileImage Answered by:- vikas_jk

Your code is not correct, I see you have copy-pasted it from various sources.

Some links

https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&ved=2ahUKEwjTqv623NLwAhVSXSsKHR52DnsQFjADegQIDxAD&url=http%3A%2F%2Fwww.cs.ucdavis.edu%2F~gusfield%2Fpphcd%2FE%3A%2Fhpph%2Fstackar.c&usg=AOvVaw347DRAcC8Q3IA2egSzzvME

Please provide a valid code with a proper explanation of the description, so anyone can help you correctly

Here is Infix to postfix using all three brackets

#include<stdio.h>
#include<ctype.h>

char stack[100];
int top = -1;

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

char pop()
{
    if(top == -1)
        return -1;
    else
        return stack[top--];
}

int priority(char x)
{
    if(x == '(' || x== '{' || x == '[')
        return 0;
    if(x == '+' || x == '-')
        return 1;
    if(x == '*' || x == '/')
        return 2;
    return 0;
}

int main()
{
    char exp[100];
    char *e, x;
    printf("Enter the expression : ");
    scanf("%s",exp);
    printf("\n");
    e = exp;
    
    while(*e != '\0')
    {
        if(isalnum(*e))
            printf("%c ",*e);
        else if(*e == '(' || *e == '{' || *e == '[')
            push(*e);
        else if(*e == ')')
        {
            while((x = pop()) != '(')
                printf("%c ", x);
        }
        else if(*e == '}')
        {
              while((x = pop()) != '{')
                printf("%c ", x);
        }
         else if(*e == ']')
        {
              while((x = pop()) != '[')
                printf("%c ", x);
        }
        else
        {
            while(priority(stack[top]) >= priority(*e))
                printf("%c ",pop());
            push(*e);
        }
        e++;
    }
    
    while(top != -1)
    {
        printf("%c ",pop());
    }return 0;
}

Output:

Enter the expression : {A*C}-[B*D]

A C * B D * - 

You can test it here https://onlinegdb.com/4R-PmRAVa

Thanks

1
At:- 5/18/2021 8:04:34 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly