Cod sursa(job #271586)

Utilizator UpL1nKPaunescu Sorin UpL1nK Data 5 martie 2009 16:20:15
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

char buffer[10000];
long length;
char *c;

long expresie();
long termen();
long factor();

int main() {

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

    fin.get(buffer, 100001);
    buffer[strlen(buffer)] = 0;
    length = strlen(buffer);

    c = buffer;

    fout<<expresie();

    return 0;
}


long expresie() {

    long x = termen();
    while ((*c == '+' || *c == '-') && (c-buffer+1 <= length)) {
	if (*c == '+') {
	    c++;
	    x += termen();
	} else if (*c == '-') {
	    c++;
	    x -= termen();
	}
    }

    return x;


}

long termen() {

    long x=factor();
    while ((*c == '*' || *c == '/') && (c-buffer+1 <= length)) {
	if (*c == '*') {
	    c++;
	    x = x * factor();
	} else if (*c == '/') {
	    c++;
	    x = x / factor();
	}
    }

    return x;

}

long factor() {

    long aux;
    if (isdigit(*c)) {
	aux = atof(c);
	while (isdigit(*c))
	    c++;
    } else {
	if (c-buffer+1 <= length) {
	    c++;
	    aux = expresie();
	    c++;
	}
    }

    return aux;

}