Cod sursa(job #1491982)

Utilizator gabi.cristacheGabi Cristache gabi.cristache Data 26 septembrie 2015 20:51:10
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.23 kb
#include <fstream>
#include <stack>
#include <sstream>
#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

int getPrecedence(char c) {
    return (c == '*' || c == '/');
}

int main()
{
    char c;
    int number = 0;
    stringstream ss;
    stack<char> mystack;

    string expression;
    fin >> expression;

    for (int i = 0; i < expression.length(); ++i) {
        char c = expression[i];

        if ('0' <= c && c <= '9') {
            while (i < expression.length() && '0' <= expression[i] && expression[i] <= '9') {
                number = number * 10 + (expression[i] - '0');
                ++i;
            }
            ss << number << ' ';
            number = 0;
            --i;
        } else {

            if (c == '(') {
                mystack.push('(');
            } else if (c == ')') {
                while (mystack.top() != '(') {
                    ss << mystack.top() << ' ';
                    mystack.pop();
                }
                mystack.pop();
            } else {
                while (!mystack.empty() && mystack.top() != '(' && getPrecedence(mystack.top()) >= getPrecedence(c)) {
                    ss << mystack.top() << ' ';
                    mystack.pop();
                }
                mystack.push(c);
            }
        }
    }

    while (!mystack.empty()) {
        ss << mystack.top() << ' ';
        mystack.pop();
    }

    string token;

    stack<int> evalStack;
    while (ss >> token) {
        if ('0' <= token[0] && token[0] <= '9') {
            evalStack.push(atoi(token.c_str()));

        } else {
            int a = evalStack.top();
            evalStack.pop();
            int b = evalStack.top();
            evalStack.pop();

            if (token == "+") {
                evalStack.push(a + b);
            } else if (token == "-") {
                evalStack.push(b - a);
            } else if (token == "*") {
                evalStack.push(a * b);
            } else if (token == "/") {
                evalStack.push(b / a);
            }
        }
    }

    fout << evalStack.top() << endl;

    return 0;
}