Pagini recente » Cod sursa (job #1481081) | Cod sursa (job #305519) | Cod sursa (job #322204) | Cod sursa (job #2598491) | Cod sursa (job #2650699)
#include<fstream>
#include<iostream>
#include<string.h>
#include<ctype.h>
#include<stack>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char expresie[300000],postfix[300000];
int p;
int prioritate(char c)
{
if (strchr("+-", c))
return 1;
else
if (strchr("*/", c))
return 2;
else
return -10;
}
bool isOperator(char c)
{
if(strchr("()+-*/",c))
return true;
else
return false;
}
void ordine_poloneza(char s[])
{
stack <char> semne;
semne.push('s');
char* s1 = s;
while (*s1 != '\0')
if (isOperator(*s1))
{
if (*s1 == '(')
semne.push(*s1);
else
if (*s1 == ')')
{
do
{
postfix[p++] = semne.top();
postfix[p++] = ' ';
semne.pop();
} while (semne.top() != '(');
semne.pop();
}
else
if (prioritate(*s1) > prioritate(semne.top()))
semne.push(*s1);
else {
while (semne.top() != 's' && prioritate(*s1) <= prioritate(semne.top()))
{
postfix[p++] = semne.top();
postfix[p++] = ' ';
semne.pop();
}
semne.push(*s1);
}
s1++;
}
else
{
while (!isOperator(*s1))
{
postfix[p++] = *s1;
s1++;
}
postfix[p++] = ' ';
}
while (semne.top() != 's')
{
postfix[p++] = semne.top();
postfix[p++] = ' ';
semne.pop();
}
postfix[--p] = '\0';
}
int main()
{
f.getline(expresie, 100);
ordine_poloneza(expresie);
char* next=NULL;
char* cuv = strtok_s(postfix, " ", &next);
stack <long long> stiva;
while (cuv)
{
if (!isOperator(*cuv))
stiva.push(atol (cuv));
else
{
long long nod1 = stiva.top();
stiva.pop();
long long nod2 = stiva.top();
stiva.pop();
if (*cuv == '+')
stiva.push(nod2 + nod1);
else
if (*cuv == '-')
stiva.push(nod2 - nod1);
else
if (*cuv == '*')
stiva.push(nod2 * nod1);
else
stiva.push(nod2 / nod1);
}
cuv = strtok_s(NULL, " ",&next);
}
g << stiva.top();
f.close();
g.close();
return 0;
}