Click to See Complete Forum and Search --> : Infix to Postfix Problems


Arcane_Disciple
03-13-2003, 02:27 PM
I am trying to convert a infix expression to postfix. The numbers print out fine, but olny the operators in () and the last opperator print. Why?


#include <iostream>
#include <sstream> // defines the istringstream class
#include <stack> // defines the stack<T> class template
using namespace std;

int main()
{ stack<char> opStack; // stack for operators
string s;
cout << "Enter an infix expression: ";
getline(cin,s);
istringstream in(s); // convert input to stringstream
char c;
while (in >> c)
{
if (c=='+' || c=='-' || c=='*' || c=='/' || c=='^')
{
opStack.push(c);
}
else if (c==')')
{
cout << opStack.top() << " ";
opStack.pop();
}
else if (c>='0' && c<= '99')
{
in.putback(c);
int n;
in >> n;
cout << n << " ";
}
}
cout << opStack.top()<< endl;
}
//******************************

Arcane_Disciple
03-13-2003, 02:50 PM
after posting it on here I realized that I am only poping opStack at the very end. That explains why only the last operation prints. This still leaves me with the problem of how to display the other operations in the right spot.

fishhead
03-14-2003, 09:01 AM
Put the numbers in the same stack as the operators.