I have a program that is supposed to convert an expression into reverse polish notation, and then display the answer after performing the calculations. Right now it doesn't perform calculations correctly. For example, if I enter 5+2+5, it only registers the 5+2 for some reason. Can anyone tell me what I did wrong?
#include <iostream>
#include <stack>
void calculation(int, int, char);
using namespace std;
stack<int> a;
void main(void)
{
bool expression = false;
char ch;
char done;
int op1, op2;
cout << "Reverse Polish Notation : " << endl;
cout << "Enter expression: " << endl;
while (!expression)
{
cin >> op1;
cin >> op2;
cin >> ch;
calculation(op1, op2, ch);
if (!cin)
expression = false;
else
{
expression = true;
calculation(op1, op2, ch);
}
}
cout << "Your expression is " << a.top() << endl;
}
void calculation(int oper1, int oper2, char chr)
{
switch (chr)
{
case '+':
a.push(oper1 + oper2);
break;
case '-':
a.push(oper1 - oper2);
break;
case '*':
a.push(oper1 * oper2);
break;
case '/':
a.push(oper1 / oper2);
break;
}
}
Your program does not convert anything. It is a very simple RPN calculator that takes a single term consisting of two operands and a binary operation and calculate the results.
If you need it to take more complex RPN inputs, you need to re-design the input and calculation logic.
If you want to input infix expressions like 5+4
but keep the internal representation as an RPN-stack, you will also have to write a parser which does that.