0

hi guys im having difficulties about plus sign while getting input. here im dealing with reverse polish notation calculator. what i have to is to take input as "3 2 + $" which means(in an easy way) add 3 and 2 and show them. i tried to use stringstreams, while(cin). now im trying to get input one by one;

int num;
char ch;
while (cin)
    {
        if (cin >> num)
        {
            cout<<num;
        }
        else
        {
            cin.clear();
            cin >> ch;
            cout << ch;
        }
    }
}

it doesnt work for + and - and works for * and /. but i need those operands too. i tried istringstream by gettingline. it didnt see + or - either.

1 Answers1

2

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;
}
NetVipeC
  • 4,402
  • 1
  • 17
  • 19