Pagini recente » Cod sursa (job #22169) | Cod sursa (job #373441) | Cod sursa (job #3271641) | Cod sursa (job #309413) | Cod sursa (job #667974)
Cod sursa(job #667974)
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
string str;
int i;
stack <int> result;
stack <char> ops;
ofstream out("evaluare.out");
bool is_digit (char c)
{
if (c>=48 && c<=57)
return true;
return false;
}
bool is_operator (char c)
{
if(c=='+'||c=='-'||c=='/'||c=='*')
return true;
return false;
}
int is_bracket (char c)
{
if(c=='(')
return -1;
if(c==')')
return 1;
return 0;
}
int priority (char c)
{
switch (c)
{
case '-': return 0;
case '+': return 1;
case '*': return 2;
case '/': return 3;
}
return -1;
}
int comp(int a, int b, char c)
{
out << b << c << a << "\n";
/*switch (c)
{
case '+': cout << int(b+a);
case '-': cout << int(b-a);
case '/': cout << int(b/a);
case '*': cout << int(b*a);
}*/
if(a==0&&c=='/')
return 0;
switch (c)
{
case '+': return (b+a);
case '-': return (b-a);
case '/': return (b/a);
case '*': return (b*a);
}
}
void pop_out()
{
int a = result.top();
result.pop();
int b = result.top();
result.pop();
result.push(comp(a,b,ops.top()));
ops.pop();
}
int main()
{
ifstream in("evaluare.in");
getline(in,str);
in.close();
int len = str.size();
while(i<len)
{
if(is_digit(str[i]))
{
int temp = str[i]-48;
++i;
while(is_digit(str[i]))
{
temp = temp*10+str[i]-48;
++i;
}
result.push(temp);
}
//cout <<is_bracket(str[i]) << " " << i << " " << str[i];
if(is_bracket(str[i])<0)
{
ops.push('(');
++i;
}
if(is_operator(str[i]))
{
if(ops.empty())
ops.push(str[i]);
else
{
while (!ops.empty()&&priority(ops.top())>priority(str[i]))
{
pop_out();
}
ops.push(str[i]);
}
//cout << ops.top();
++i;
}
if(is_bracket(str[i])>0)
{
while(ops.top()!='(')
{
pop_out();
}
ops.pop();
++i;
}
}
//cout << result.size() << " " << ops.size() << " " << ops.top() << " " << result.top() << " ";
while(!ops.empty())
{
}
cout << result.top();
return 0;
}