Cod sursa(job #1831556)

Utilizator AlexandruLuchianov1Alex Luchianov AlexandruLuchianov1 Data 18 decembrie 2016 12:05:01
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
#include <iostream>
#include <fstream>
#include <stdio.h>

using namespace std;

//freopen("evaluare.in","r",stdin);
//ifstream in ("evaluare.in");
ofstream out ("evaluare.out");

int n= 0;
int const NMAX = 100002;
char currentChar;

void readNextChar() {
  currentChar = getc(stdin);// '\0' >>ch //tema cu stream
}

int integer(int result = 0) { //acumulator
  if('0' <= currentChar && currentChar <= '9'){
    int digit = currentChar-'0';
    readNextChar();
    return integer(result*10 + digit);
  } else {
    return result;
  }
}

int suma(int result = 0, char op = '+');
//Factor = (Suma) sau Integer
int factor(){
  int result = 0;
  if(currentChar=='(') {
    readNextChar();
    result =  suma();
    readNextChar();
  } else{
    result =  integer();
  }
  return result;
}


int produs(int result = 1, char op = '*');

int suma(int result, char op ) {
  if(op=='+')
   result = result + produs();
  else if(op=='-')
   result = result - produs();
  if(currentChar == '+' || currentChar == '-'){
    op = currentChar;
    readNextChar();
    result = suma(result, op);
  }
  return result;
}

//Prod = Factor * Factor * Factor * .. * Factor
int produs(int result, char op) { //1OP{prod}
  if(op=='*')
   result = result * factor();
  else if(op=='/')
   result = result / factor();
  if(currentChar == '*' || currentChar == '/'){
    op = currentChar;
    readNextChar();
    result = produs(result, op);
  }
  return result;
}

//8/4*2
//8/(4*2)
int produs_right(){ //right associativity ^ are asociativitate la dreapta
  int result = factor();

  if(currentChar == '*'){
    readNextChar();
    return result * produs();
  }
  if(currentChar == '/'){
    readNextChar();
    return result / produs();
  }else
    return result;
}

int main() {
  freopen("evaluare.in","r",stdin);
  readNextChar();
  out<<suma()<<endl;
  return 0;
}

int integer_iterative() {
  int result = 0;
  while('0' <= currentChar && currentChar <= '9'){
    result = result * 10 + currentChar - '0';
    readNextChar();
  }
  return result;
}