| while there are more characters in the input { Read next symbol ch in the given infix expression. If ch is an operand put it on the output. If ch is an operator i.e.* , /, +, -, or ( { If stack is empty push ch onto stack; Else check the item op at the top of the stack; while (more items in the stack && priority(ch) <= priority (op) ) { pop op and append it to the output, provided it is not an open parenthesis op = top element of stack } push ch onto stack } If ch is right parenthesis ‘)’ Pop items from stack until left parenthesis reached Pop left parenthesis and discard both left and right parenthesis }/* now no more characters in the infix expression*/ Pop remaining items in the stack to the output. |
#include <iostream>
#include <conio.h>
#include <stack>
#include <string>
using namespace std;
int priority(char a)
{
int temp;
if( a=='^')
temp = 1;
else
{
if(a=='*' || a=='/')
temp = 2;
else
{
if(a=='+' || a=='-')
temp = 3;
}
}
return temp;
}
int main()
{
string infix;
cout << "Enter an arithmetic expression: " << endl;
cin >> infix;
stack<char> temp;
stack<char> postfix;
int i;
for (i=0; i<11; i++)
{
if (infix[i]!='+' || infix[i]!='-' || infix[i]!='*' || infix[i]!='/' || infix[i]!='^' || infix[i]!='(' || infix[i]!=')')
{postfix.push(infix[i]);
cout << postfix.top();}
else
{
if (infix[i]=='(')
temp.push(infix[i]);
else
{
if (infix[i]=='+' || infix[i]=='-' || infix[i]=='*' || infix[i]=='/' || infix[i]!='^')
{
while (priority(temp.top()) <= priority(infix[i]))
{
postfix.push(infix[i]);
cout << postfix.top();
temp.pop();
}
temp.push(infix[i]);
}
else if(infix[i]==')')
{
while (temp.top() != '(')
{
postfix.push(infix[i]);
cout << postfix.top();
temp.pop();
}
temp.pop();
}
}
}
}
getch();
return 0;
} |
for (i=0; i<11; i++) Why 11? Shouldn't this be infix.lenght() ? |
|
infix[i]!='^'.postfix.push(infix[i]);.| Progesco wrote: |
|---|
| Pop remaining items in the stack to the output. |
cin.ignore(numeric_limits<streamsize>::max(), '\n'); |
|