Pagini recente » Cod sursa (job #2000587) | Cod sursa (job #2432748) | Cod sursa (job #1862185) | Cod sursa (job #2935074) | Cod sursa (job #2002019)
#include <fstream>
#include <string>
#include <stack>
#include <sstream>
using namespace std;
void main() {
ifstream in("evaluare.in");
char infix[100000];
in >> infix;
stack<char> operators;
string postfix;
char *p = infix;
while (*p) {
if (isdigit(*p)) {
long val = strtol(p, &p, 0);
postfix.insert(postfix.end()-postfix.begin(),' '+ to_string(val));
}
else {
switch (*p)
{
case '+':
case '-':
if (operators.top() == '*' || operators.top() == '/')
while (operators.top()!='(') {
postfix.insert(postfix.end(), 1, ' ');
postfix.insert(postfix.end(), 1, operators.top());
operators.pop();
if (operators.empty()) break;
}
operators.push(*p);
break;
case ')':
while (operators.top() != '(')
{
postfix.insert(postfix.end(), 1, ' ');
postfix.insert(postfix.end(), 1, operators.top());
operators.pop();
}
operators.pop();
break;
default:
operators.push(*p);
break;
}
p++;
}
}
while (!operators.empty())
{
postfix.insert(postfix.end(), 1, ' ');
postfix.insert(postfix.end(), 1, operators.top());
operators.pop();
}
istringstream pf(postfix);
stack<long> numbers;
while (!pf.eof()){
string temp;
pf >> temp;
if (temp[0] <= 57 && temp[0] >= 48) numbers.push(stol(temp));
else {
long c = 0;
switch (temp[0])
{
case('+'):
c += numbers.top();
numbers.pop();
c += numbers.top();
numbers.pop();
numbers.push(c);
break;
case('-'):
c -= numbers.top();
numbers.pop();
c += numbers.top();
numbers.pop();
numbers.push(c);
break;
case('*'):
c = numbers.top();
numbers.pop();
c = numbers.top()*c;
numbers.pop();
numbers.push(c);
break;
case('/'):
c = numbers.top();
numbers.pop();
c = numbers.top()/c;
numbers.pop();
numbers.push(c);
break;
default:
break;
}
}
}
ofstream out("evaluare.out");
out<<numbers.top();
}