开发者

infix to postfix

开发者 https://www.devze.com 2023-01-21 15:05 出处:网络
I\'ve been trying to figure out this problem. I have an assignment to make a basic calculator. To do so i need the instructions in postfix.

I've been trying to figure out this problem. I have an assignment to make a basic calculator.

To do so i need the instructions in postfix. I have found some code online, which worked but used gets().

I tried replacing the gets... but the program no longer works. Here is the code, i was hoping someone could find the error (using 2+4 as the input, it reads and recognizes 2 as a digit, then + as an operator, then 4 as a digit... then gets stuck in a loop somewhere along the line)

To be clear, using this code is fair game for my assignment, as long as I cite is as a reference (because it is only a small part).

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

#define MAX 10
#define EMPTY -1

struct stack
{
    char data[MAX];
    int top;
};

int isempty(struct stack *s)
{
    printf("isempty\n");
    return (s->top == EMPTY) ? 1 : 0;
}

void emptystack(struct stack* s)
{
    printf("emptystack\n");
    s->top=EMPTY;
}

void push(struct stack* s,int item)
{
    printf("push\n");
    if(s->top == (MAX-1))
    {
        printf("\nSTACK FULL");
    }
    else
    {
        printf("add to stack\n");
        ++s->top;
        s->data[s->top]=item;
    }
}

char pop(struct stack* s)
{
    printf("pop\n");
    char ret=(char)EMPTY;
    if(!isempty(s))
    {
        ret= s->data[s->top];
        --s->top;
    }
    return ret;
}

void display(struct stack s)
{
    printf("display\n");
    while(s.top != EMPTY)
    {
        printf("not empty\n");
        printf("\n%d",s.data[s.top]);
        s.top--;
    }
}

int isoperator(char e)
{
    getchar();
    printf("isoperator\n");
    if(e == '+' || e == '-' || e == '*' || e == '/' || e == '%')
        return 1;
    else
        return 0;
}


int priority(char e)
{
    printf("priority\n");
    int pri = 0;

    if(e == '*' || e == '/' || e =='%')
        pri = 2;
    else
    {
        if(e == '+' || e == '-')
            pri = 1;
    }
    return pri;
}

void infix2postfix(char* infix, char * postfix, int insertspace)
{
    printf("in infix2postfix\n");
    char *i,*p;
    struct stack X;
    char n1;
    emptystack(&X);
    i = &infix[0];
    p = &postfix[0];

    while(*i)
    {
        while(*i == ' ' || *i == '\t')
        {
            i++;
        }

        if( isdigit(*i) || isalpha(*i) )
        {
            printf("is digit.\n");
            while( isdigit(*i) || isalpha(*i))
            {
                *p = *i;
            开发者_开发问答    p++;
                i++;
            }
            /*SPACE CODE*/
            if(insertspace)
            {
                *p = ' ';
                p++;
            }
            /*END SPACE CODE*/
        }

        if( *i == '(' )
        {
            push(&X,*i);
            i++;
        }

        if( *i == ')')
        {
            n1 = pop(&X);
            while( n1 != '(' )
            {
                *p = n1;
                p++;
                /*SPACE CODE*/
                if(insertspace)
                {
                    *p = ' ';
                    p++;
                }
                /*END SPACE CODE*/
                n1 = pop(&X);
            }
            i++;
        }

        if( isoperator(*i) )
        {
            if(isempty(&X))
                push(&X,*i);
            else
            {
                n1 = pop(&X);
                while(priority(n1) >= priority(*i))
                {
                    *p = n1;
                    p++;
                    /*SPACE CODE*/
                    if(insertspace)
                    {
                        *p = ' ';
                        p++;
                    }
                    /*END SPACE CODE*/
                    n1 = pop(&X);
                }
                push(&X,n1);
                push(&X,*i);
            }
            i++;
        }
    }
    while(!isempty(&X))
    {
        n1 = pop(&X);
        *p = n1;
        p++;
        /*SPACE CODE*/
        if(insertspace)
        {
            *p = ' ';
            p++;
        }
        /*END SPACE CODE*/
    }
    *p = '\0';
}

int main()
{
    char in[50],post[50],temp[50];

    strcpy(&post[0],"");
    printf("Enter Infix Expression : ");
    fflush(stdin);
    fgets(in,50,stdin);
    printf("%s",in);
    infix2postfix(&in[0],&post[0],1);
    printf("Postfix Expression is : %s\n",&post[0]);

    return 0;
}

Thanks for the help, i really appreciate it :).


fgets() includes a newline in the string when it gets to one, so you've got a string reading "2+4\n". Replace the while (*i) with while (*i && *i != '\n') and see where that gets you.


#include<stdio.h>
char stack[100];
int lowerBound=0;
int upperBound=99;
int top=upperBound+1;
int size=0;  
char postFix[101];
int postFixLowerBound=0;
void push(char op)
{
  top--;
  stack[top]=op;
  size++;
}
char pop()
{
 char op;
 op=stack[top];
 top++;
 size--;
 return op;
 }
 int isEmpty()
{
  return top==upperBound+1;
}
 int isOperator(char c)
 {
   return(c=='^'||c=='/'||c=='*'||c=='+'||c=='-');
  }
 int isOperand()
 {
    if(isOperator(c)) return 0;
   else return 1;
 }
 int getPrecedenceLevel(char op)
 {
    if(op=='^') return 3;
    if(op=='/' || op=='*') return 2;
    if(op=='+' || op=='-') return 1;
    return 0;
 }
 int getElementAtTop()
 {
   return stack[top];
 }
 void appendToPostFixString(char c)
 {
  postFix[postFixLowerBound]=c;
  postFixLowerBound++;
  postFix[postFixLowerBound]='\0';
 }
  void main()
  {
   char infix[101];
   char c,op;
   int i;
   printf("Enter an infix expression\n");
   scanf("%s",infix);
   i=0;
   while(infix[i]='\0')
   {
    c=infix[i];
    i++;
    if(c=='(')
    {
      push(c);
      continue;
     }
      if(c==')')
     {
       while(1)
      {
       op=pop();
      if(op=='(')
      {
      op=pop();
      if(op=='(')
      {
        break;
      } 
      appendToPostFixString(op);
    }
    continue;
  }
  if(isOperand(c))
  {
    appendToPostFixString(c);
    continue;
  }
  if(isOperator(c))
  {
   if(isEmpty())
   {
     push(c);
   }
   else
   {
     op=getElementAtTop();
     if(op=='(')
     {
       push(c);
     }
     else
     {
       if(getPrecedenceLevel(op)>=getPrecedenceLevel(c))
       {
         while(1)
         {
           if(isEmpty())
           {
             break;
           } 
           op=getElementAtTop();
           if(op=='(')
           {
             break;
           }
           if(getPrecedenceLevel(op)<getPrecedenceLevel(c))
           {
             break;
           }
           op=pop();
           appendToPostFixString(op);
         }
         push(c);
       }
       else
       {
         push(c);
       }
     }
   }
   continue;
  }//while ends
  while(1)
  {
    if(isEmpty())
    {
      break;
    }
 op=pop();
 appendToPostFixString(op);
 }
 printf("Post Fix Expression is \n");
 printf("%s",postFix);
}


#include<stdio.h>
#include<string.h>
// This function will check if op1 has higher precedence than op2
int isHigherPrecedence(char op1, char op2)
{
    int n1, n2;
    if(op1 == '^') n1 = 3;
    if(op2 == '^') n2 = 3;
    if(op1 == '*' || op1 == '/') n1 = 2;
    if(op2 == '*' || op2 == '/') n2 = 2;
    if(op1 == '+' || op1 == '-') n1 = 1;
    if(op2 == '+' || op2 == '-') n2 = 1;
    if(op1 == '(') n1 = 0;
    if(op2 == '(') n2 = 0;
    return n1 > n2;
}
// Function to check if op is an operator
int isOperator(char op)
{
  if(op == '+' || op == '-' || op == '^') return 1;
  if(op == '%' || op == '/' || op == '*') return 1;
  return 0;
}

void infixToPostfix(char *str)
{
    int i, top = -1;
    char postfix[50] = "", stack[50];

    printf("\nPostfix = ");

    // Scanning each character of str from left to right
    for(i = 0; i < strlen(str); i++)
    {
        if(str[i] == '(')
            stack[++top] = '('; 

        else if(str[i] == ')')
        {
            // Pop all the elements until it reaches '('
            // and print each element before it is pop
            while(stack[top] != '(')
                printf("%c", stack[top--]);
            top--; // this is to remove '('
        }
        // if Operator
        else if(isOperator(str[i]))
        {
            // the operator to be pushed on to the top of 
            // the stack should have the highest precedence
            while(top != -1 && !isHigherPrecedence(str[i], stack[top]))
                printf("%c", stack[top--]);
            stack[++top] = str[i];
        }
        // if operand
        else printf("%c", str[i]);
    }
    // pop out the remaining operators on the stack
    while(top != -1)
        printf("%c", stack[top--]);
}
int main()
{
    char infixExp[50];
    infixToPostfix("A+(B*C)");
    infixToPostfix("A+(B*C-(D/E^F)*G)*H");
    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消