Pagini recente » Cod sursa (job #591861) | Cod sursa (job #3161030) | Cod sursa (job #2586799) | Cod sursa (job #65902) | Cod sursa (job #2650696)
#include<fstream>
#include<iostream>
#include<string.h>
#include<ctype.h>
#include<stack>
using namespace std;
ifstream f("pol.in");
ofstream g("pol.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;
char* cuv = strtok(postfix, " ");
stack <int> stiva;
while (cuv)
{
if (!isOperator(*cuv))
stiva.push(atoi(cuv));
else
{
int nod1 = stiva.top();
stiva.pop();
int nod2 = stiva.top();
stiva.pop();
cout << nod1 << " " << nod2 << endl;
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(NULL, " ");
}
g << stiva.top();
f.close();
g.close();
return 0;
}