我收到一个分段错误,说 core dumped 。C++ 程序是要隐藏一个中缀表达式。我想逻辑是正确的。我检查了代码,但无法找出错误。我有优先级函数来计算运算符的优先级,函数 ifpf 将中缀表达式转换为后缀表达式。
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#define size 100
using namespace std;
class stack{
char pstack[size];
int top;
public:
stack(){
int top=-1;
}
void push(char item){
if(top==size) {cout<<"Stack is already full";exit(0);}
else {pstack[++top]=item;}
}
char pop(){
char ch='#';
if(top==-1) cout<<"Stack is empty...";
else { ch=pstack[top--];}
return ch;
}
int precedence(char ch){
switch(ch){
case '(' : return 1;
case ')' : return 2;
case '+' :
case '-' : return 3;
case '*' :
case '/' :
case '%' : return 4;
case '^' : return 5;
default : return 0;
}
}
void ifpf(){
int len,priority,i,j=0;
char infix[size],ch,postfix[size];
cout<<"Enter the infix expression : "<<endl;
cin>>infix;
len=strlen(infix);
infix[len++]=')';
push('(');
for(i=0,j=0;i<len;i++){
switch(precedence(infix[i])){
case 1 : push(infix[i]);break;
case 2 : ch=pop();
while(ch!='('){
postfix[j++]=ch;ch=pop();
}
break;
case 3 : ch=pop();
while(precedence(ch)>=3){
postfix[j++]=ch;ch=pop();
}
push(ch);
push(infix[i]);
break;
case 4 : ch=pop();
while(precedence(ch)>=4){
postfix[j++]=ch;ch=pop();
}
push(ch);
push(infix[i]);
break;
case 5 : ch=pop();
while(precedence(ch)==5){
postfix[j++]=ch;ch=pop();
}
push(ch);
push(infix[i]);
break;
default : postfix[j++]=infix[i];break;
}
}
cout<<"The post fix wxpression is : ";
cout<<postfix;
}
};
int main(){
stack obj;
obj.ifpf();
return 0;
}