Cod sursa(job #724388)
//============================================================================
// Name : ExprEval.cpp
// Author : Petrisor Teodora
// Version :
// Copyright :
// Description : Hello World in C++, Ansi-style
//============================================================================
#include<fstream>
using namespace std;
const long int MAX = 100010; // declare maximum size of string
char expr[MAX], *p = expr; // reserve space for string and declare pointer to beginning of string
long term(); // declare needed functions
long factor();
/*
* Adds all the terms of an expression
*/
long evaluate()
{
long r = term();
while(*p == '+' || *p == '-')
{
switch(*p)
{
case '+':
++p; // go over the plus sign
r += term(); // add what follows
break;
case '-':
++p; // go over the minus sign
r -= term(); // subtract what follows
break;
}
}
return r;
}
/*
* Deals with the contents of a term, which is composed of multiplied/divided factors
*/
long term()
{
long r = factor();
while(*p == '*' || *p == '/')
{
switch(*p)
{
case '*':
p ++;
r *= factor();
break;
case '/':
p++;
r /= factor();
break;
}
}
return r;
}
/*
* Returns the value of a factor, which can be either a subexpression OR a natural number
*/
long factor()
{
long r = 0;
if(*p == '(') // if we have a subexpression
{
++p; // go over bracket
r = evaluate(); // evaluate subexpression
++p; // go over closing bracket
}
else
{
while( *p >= '0' && *p <= '9') // if we have a number
{
r = r * 10 + *p - '0'; // obtain the value
++p;
}
}
return r;
}
int main()
{
ofstream output("evaluare.out");
fgets(expr, MAX, fopen("evaluare.in", "r"));
output<<evaluate();
output.close();
return 0;
}