View Code of Problem 94

#include <cctype>
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

int main(void)
{
    stack<char> cc;
    stack<int> num;
    string str;
    getline(cin, str);
    int cnt = 0;
    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] == '(' || str[i] == ' ')
        {
            if (str[i] == '(')
                cnt = 0;
            continue;
        }
        else if (isdigit(str[i]))
        {
            cnt++;
            num.push(str[i] - '0');
            if (cnt >= 2)
            {
                int a = num.top();
                num.pop();
                int b = num.top();
                num.pop();
                if (cc.top() == '+')
                    num.push(b + a);
                else if (cc.top() == '-')
                    num.push(b - a);
                else if (cc.top() == '*')
                    num.push(b * a);
                else
                    num.push(b / a);
            }
        }
        else if (str[i] == ')')
        {
            if(cc.size() > 1)

            cc.pop();
        }
        else
        {
            cc.push(str[i]);
        }
    }
    while (num.size() != 1)
    {
        int a = num.top();
        num.pop();
        int b = num.top();
        num.pop();
        if (cc.top() == '+')
            num.push(b + a);
        else if (cc.top() == '-')
            num.push(b - a);
        else if (cc.top() == '*')
            num.push(b * a);
        else
            num.push(b / a);
    }
    cout << num.top() << endl;
}

Double click to view unformatted code.


Back to problem 94