中缀到后缀

发布于 2024-09-28 12:47:42 字数 4143 浏览 4 评论 0原文

我一直在试图解决这个问题。 我有一个任务是制作一个基本计算器。

为此,我需要 postfix 中的说明。 我在网上找到了一些代码,该代码有效但使用了 gets()。

我尝试更换 gets... 但程序不再工作。这是代码,我希望有人能找到错误(使用 2+4 作为输入,它读取并识别 2 作为数字,然后 + 作为运算符,然后 4 作为数字......然后陷入困境沿线某处循环)

要明确的是,使用此代码对于我的作业来说是公平的游戏,只要我引用它作为参考(因为它只是一小部分)。

#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;
}

感谢您的帮助,我真的很感激:)。

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 :).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北斗星光 2024-10-05 12:47:42

fgets() 当字符串到达​​ 1 时,会在字符串中包含一个换行符,因此您将得到一个显示为“2+4\n”的字符串。将 while (*i) 替换为 while (*i && *i != '\n') 并看看结果如何。

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.

聊慰 2024-10-05 12:47:42
#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>
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);
}
北方的韩爷 2024-10-05 12:47:42
#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;
}
#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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文