Your pop is totally screwed up.
Why would you pass stack[top] to it? Since stack is global, pop doesn't need any parameters.
Why doesn't pop return anything?
Since you pre-increment top for the push you need to post-decrement top for the pop.
And the assignment is basically backwards, to. You don't want to assign anything to the stack during a pop.
#include<iostream>
usingnamespace 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;
}
elseif(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;
}
Many of the functions you’ve implemented already exist in the standard library for std::strings, so I’ve substituted those for yours.
std::string::pop_back() --> deletes last character
std::string::push_back() --> append one character (the same as ‘+=’)
std::string::back() --> returns (a reference to) the last character.
The range-for loop in line 20 helps avoiding using indexes.
Apart from what’s above, I’ve left your code nearly unchanged, but I added output statements which could help you to guess what could be the error.
@Enoizat wow, i thought those functions where different from #include<stack> functions, didn't know it could also be applied. thank you very much for the detailed explanation, i could now trace what went wrong.
@newguy17, I'd avoid doing cin stuff for now. Just have a bunch of hardcoded examples and incrementally improve the functionality until expected matches actual (keyword: bunch). You probably want a method to show the stack, showing it constantly to prove what should be stored is stored (there's always the debugger, too).