Pagini recente » Cod sursa (job #2592431) | Cod sursa (job #1947386) | Cod sursa (job #160344) | Cod sursa (job #426979) | Cod sursa (job #1619928)
#include <iostream>
#include <stack>
#include <string>
#include <fstream>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
string s;
int i;
int prio[1001];
stack<int> st ;
stack<char> op ;
void eval()
{
int n=0;
while(isdigit(s[i]))
{
n = n*10 + (s[i]-'0');
i++;
}
i--;
st.push(n);
// cout<<n<<' ';
}
void calc()
{
int x=st.top(); st.pop();
int y=st.top(); st.pop();
char c = op.top();
op.pop();
if(c=='+') st.push(y+x);
if(c=='-') st.push(y-x);
if(c=='/') st.push(y/x);
if(c=='*') st.push(y*x);
}
int main()
{
in>>s;
prio['-']=prio['+']=1;
prio['*']=prio['/']=2;
for(;i<(int)s.size();i++)
{
if(isdigit(s[i]))
{
eval();
}
else if(s[i]=='(') op.push('(');
else if(s[i]==')')
{
while(op.top()!='(') calc();
op.pop(); // scoate ( din stiva
}
else
{
while(!op.empty() && prio[(int)op.top()]>prio[(int)s[i]])
calc();
op.push(s[i]);
}
}
while(!op.empty()) calc();
out<<st.top();
return 0;
}