Pagini recente » Cod sursa (job #2915411) | Cod sursa (job #2572359) | Cod sursa (job #2666199) | Cod sursa (job #517896) | Cod sursa (job #2186782)
#include<fstream>
#include<cstring>
#include<cctype>
#include<stack>
using namespace std;
#define maxStrLength 100001
char sir[maxStrLength];
const char OPEN_BRACKET = '(', CLOSED_BRACKET = ')', MULTIPLY = '*', DIVIDE = '/', ADD = '+', SUBSTRACT = '-';
stack<char> stiva;
stack<int> evaluationStack;
int priority(char character){
if(character == OPEN_BRACKET){
return 0;
}
else if(character == ADD || character == SUBSTRACT){
return 1;
}
else {
return 2;
}
}
void updateEvaluationStack(stack<int> &evaluationStack, char ope){
int second = evaluationStack.top();
evaluationStack.pop();
int first = evaluationStack.top();
evaluationStack.pop();
switch(ope){
case ADD:
evaluationStack.push(first + second);
break;
case SUBSTRACT:
evaluationStack.push(first - second);
break;
case MULTIPLY:
evaluationStack.push(first * second);
break;
case DIVIDE:
evaluationStack.push(first / second);
break;
}
}
void parseAndEvaluate(char sir[]){
int i, number, sirLength = strlen(sir);
for(i = 0; i < sirLength;){
if(isdigit(sir[i])){
number = 0;
while(i < sirLength && isdigit(sir[i])){
number = number * 10 + (sir[i++] - '0');
}
evaluationStack.push(number);
}
else if(sir[i] == OPEN_BRACKET){
stiva.push(OPEN_BRACKET);
i++;
}
else if(sir[i] == CLOSED_BRACKET){
while(!stiva.empty() && stiva.top() != OPEN_BRACKET){
updateEvaluationStack(evaluationStack, stiva.top());
stiva.pop();
}
if(!stiva.empty()){
stiva.pop();
}
i++;
}
else {
while(!stiva.empty() && priority(stiva.top()) >= priority(sir[i])){
updateEvaluationStack(evaluationStack, stiva.top());
stiva.pop();
}
stiva.push(sir[i++]);
}
}
while(!stiva.empty()){
updateEvaluationStack(evaluationStack, stiva.top());
stiva.pop();
}
}
int main(){
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
fin >> sir;
parseAndEvaluate(sir);
fout<<evaluationStack.top();
fin.close();
fout.close();
return 0;
}