Converting infix notation expression to postfix notation
I'm doing an assignment for my Data Structures course where I have to convert an infix expression to a postfix expression. I'm almost done with it but I keep getting an error when I try entering something like a+b+c
It can handle a+b and a+b*c just fine.
I'm really not sure what's wrong with it. If someone could point me in a direction or see the problem with my code, I would really appreciate it.
#include <iostream>
#include <stack>
using namespace std;
//checks priority of operators.
int priority(char e){
int pri = 0;
if(e == '*' || e == '/' || e == '%'){
pri = 2;
}else{
if(e == '+' || e == '-'){
pri = 1;
}
}
return pri;
}
void main(){
cout << "This program will convert an infix expression to a postfix expression." << endl;
cout << "Please enter your expression without any spaces." << endl;
stack<char> charStack;
char input[100];
char output[100];
char n1;
char *o;
o = &output[0];
cin >> input;
int n = 0;
while(input[n] != 0){
if(isdigit(input[n]) || isalpha(input[n])){
*o = input[n];
n++;
o++;
}
if(input[n] == '('){
charStack.push(input[n]);
n++;
}
if(input[n] == ')'){
n1 = charStack.top();
charStack.pop();
while(n1 != '('){
*o = n1;
开发者_如何学C o++;
n1 = charStack.top();
charStack.pop();
}
n++;
}
if(input[n] == '+' || input[n] == '-' || input[n] == '*' || input[n] == '/' || input[n] == '%'){
if(charStack.empty() == true){
charStack.push(input[n]);
}else{
n1 = charStack.top();
charStack.pop();
while(priority(n1) >= priority(input[n])){
*o = n1;
o++;
n1 = charStack.top();
charStack.pop();
}
charStack.push(n1);
charStack.push(input[n]);
}
n++;
}
}
while(!charStack.empty()){
*o = charStack.top();
o++;
charStack.pop();
}
*o = '\0';
cout << output << endl;
}
You don't check whether the stack is empty before popping an element in the code for operators. That's part of the problem.
By the way, it should be int main()
instead of void
, and you don't need to compare things with true
: charStack.empty() == true
is the same as charStack.empty()
.
See my comments inline.
// You can empty the stack here.
charStack.pop();
while(priority(n1) >= priority(input[n])){
...
// BUG: This line will crash if the stack is empty.
// You need to check for an empty stack.
n1 = charStack.top();
精彩评论