首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >infix to postfix expressrion不显示任何输出

infix to postfix expressrion不显示任何输出
EN

Stack Overflow用户
提问于 2018-04-29 09:11:11
回答 1查看 78关注 0票数 0

在ab+中将a+b转换为后缀表达式的中缀。

我已经盯着代码看了几个小时了,想知道为什么根本没有显示任何输出。我试着逐行复习,尽我所能,但仍然找不出原因。有没有人能指出我哪里错了,或者是我的代码没有任何意义。另外,我只被允许使用数组和字符串。

代码语言:javascript
复制
#include<iostream>
using namespace std;

string stack; //initialize stack to contain operators
int top=-1;

void push(char a){  //add/push it to stack
    top++;
    stack[top] = a;
}

char pop(){ //delete/pop the stack
    return stack[top--];
}

int order_operation(char a){ //the precedence priority

    if(a=='+' || a=='-'){
        return 1;
    }
    else if(a=='*' || a=='/'){
        return 2;
    }
    else {
        return 3;
    }
}

int main(){
    string infix,postfix;

    cout<<"infix: ";
    getline(cin,infix);

    for(int x = 0; x<infix.length(); x++){   //scan the infix for operator
        if(infix[x]=='-' || infix[x]=='+' ||infix[x]=='*' || infix[x]=='/'){
            while(!stack.empty() && order_operation(stack[top])>=order_operation(infix[x])){ //if the stack is not empty and check the precedence

                postfix+=stack[top];  //add it to postfix string
                pop();  //pop the stack operator
            }
            push(infix[x]); 
        }
        else{
            postfix+=infix[x]; //add to postfix string if its operand
        }
    }

    while(!stack.empty()){ //if the stack is not empty put it to posfix string
        postfix+=stack[top];
        pop();
    }
    cout<<postfix;
}
EN

回答 1

Stack Overflow用户

发布于 2018-04-29 09:18:31

@Carcigenicate.

  • Your pop()方法声明的
  1. 您需要添加的endl是不正确的。它应该弹出并返回堆栈顶部的实际值,并且它不应该接受参数。目前,每次弹出堆栈时都会损坏堆栈。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50082496

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档