Cod sursa(job #1413894)

Utilizator ZenusTudor Costin Razvan Zenus Data 2 aprilie 2015 10:34:38
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <string>

using namespace std;

string str;
int pos;

int evalueaza();
int termen();
int factor();

ifstream f("evaluare.in");
ofstream g("evaluare.out");

int main()
{

f >> str;
g << evalueaza() << '\n';

return 0;
}

int evalueaza()
{
    int to = termen();

    while (pos<str.size() && (str[pos] == '+' || str[pos] == '-'))
    {
        if (str[pos] == '+')
        {
            pos += 1;
            int x = termen();
            to += x;
        }
        else
        {
            pos += 1;
            int x = termen();
            to -= x;
        }
    }

    return to;
}

int termen()
{
    int to = factor();

    while (pos<str.size() && (str[pos] == '*' || str[pos] == '/'))
    {
        if (str[pos] == '*')
        {
            pos += 1;
            int x = factor();
            to *= x;
        }
        else
        {
            pos += 1;
            int x = factor();
            to /= x;
        }
    }

    return to;
}

int factor()
{
    if (str[pos] == '(')
    {
        pos += 1;
        int x = evalueaza();
        pos += 1;
        return x;
    }

    int x = 0;
    while (pos<str.size() && '0' <= str[pos] && str[pos] <= '9')
    {
        x = x * 10 + str[pos] - '0';
        pos += 1;
    }

    return x;
}