In your sample code this line worry me while (cin)
(must certain you would have and infinite cycle), in the sample code bellow (i added that when enter a blank line the program ends).
cin will get the input one word by one word, when you write in the console 3 2 + $
when you call cin >> somevariable;
would get 4 results: 3 then 2 then + and last $. Other problem when reading polish notation is that you can't predict if the next token would be number or operator, you could get: 3 2 + $
but 3 2 2 + * $
too. For this reason you need a container to storage the operands.
Here is a little working example:
#include <iostream>
#include <stack>
#include <boost/lexical_cast.hpp>
using namespace std;
int main(int argc, char *argv[]) {
string read;
std::stack<int> nums;
while (cin >> read) {
if (read.empty()) {
break;
}
else if (read == "$") {
std::cout << nums.top() << std::endl;
}
else if (read == "+" || read == "-" || read == "*" || read == "/") {
if (nums.size() < 2) {
} // error code here
int n1 = nums.top();
nums.pop();
int n2 = nums.top();
nums.pop();
if (read == "+")
nums.push(n2 + n1);
if (read == "-")
nums.push(n2 - n1);
if (read == "*")
nums.push(n2 * n1);
if (read == "/")
nums.push(n2 / n1);
}
else {
try {
nums.push(boost::lexical_cast<int>(
read)); // you should add convertion excepcion code
}
catch (...) {
}
}
}
return 0;
}