Cod sursa(job #3251742)

Utilizator BeilandArnoldArnold Beiland BeilandArnold Data 26 octombrie 2024 18:53:00
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;

const int MERET = 100001;

int tag(char *str, int &poz);
int tenyezo(char *str, int &poz);
int szam(char *str, int &poz);
void skip_space(char *str, int &poz);

int kifejezes(char *str, int &poz)
{
    int t1 = tag(str, poz);

    while (true) {
        skip_space(str, poz);

        if (str[poz] == '+') {
            poz++; // '+'
            int t2 = tag(str, poz);
            t1 += t2;
        }
        else if (str[poz] == '-') {
            poz++;
            int t2 = tag(str, poz);
            t1 -= t2;
        }
        else {
            return t1;
        }
    }
}

int tag(char *str, int &poz)
{
    int t1 = tenyezo(str, poz);

    while (true) {
        skip_space(str, poz);

        if (str[poz] == '*') {
            poz++;
            int t2 = tenyezo(str, poz);
            t1 *= t2;
        }
        else if (str[poz] == '/') {
            poz++;
            int t2 = tenyezo(str, poz);
            t1 /= t2;
        }
        else {
            return t1;
        }
    }
}

int tenyezo(char *str, int &poz)
{
    skip_space(str, poz);

    if (isdigit(str[poz]))
        return szam(str, poz);
    else if (str[poz] == '(') {
        poz++; // '(' átlépése
        int ertek = kifejezes(str, poz);

        skip_space(str, poz);

        if (str[poz] == ')') {
            poz++; // ')'
            return ertek;
        }
        else {
            cout << "hiba" << endl;
            return -1;
        }
    }
    else {
        cout << "hiba" << endl;
        return -1;
    }
}

int szam(char *str, int &poz)
{
    skip_space(str, poz);

    int ertek = 0;

    while (isdigit(str[poz])) {
        ertek = ertek*10 + (str[poz] - '0');
        poz++;
    }

    return ertek;
}

void skip_space(char *str, int &poz)
{
    while (isspace(str[poz]))
        ++poz;
}


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

    char str[MERET];
    fin.getline(str, MERET);

    int i = 0;
    fout << kifejezes(str, i) << endl;

    return 0;
}