Pagini recente » Cod sursa (job #396109) | Cod sursa (job #975253) | Cod sursa (job #2354341) | Cod sursa (job #2241061) | Cod sursa (job #1701193)
# include <fstream>
# include <iostream>
# include <algorithm>
# include <stack>
# include <string>
using namespace std;
ifstream f ( "evaluare.in" );
ofstream g ( "evaluare.out" );
int i = 0;
string s;
stack < int > st;
stack < char > sto;
void evaluare() {
int n = 0;
while ( s[i] <= '9' && s[i] >= '0' ) {
n = n * 10 + ( s[i] - '0' );
++ i;
}
st.push( n );
-- i;
}
void calcul(){
int y = st.top(); st.pop();
int x = st.top(); st.pop();
char op = sto.top(); sto.pop();
if ( op == '+' ) st.push( x + y );
else if ( op == '-' ) st.push( x - y );
else if ( op == '*' ) st.push( x * y );
else if ( op == '/' ) st.push( x / y );
}
int main()
{
f >> s;
vector < int > p( 260, 0 );
p['+'] = 1;
p['-'] = 1;
p['*'] = 2;
p['/'] = 2;
for ( ; i < s.size(); ++ i ) {
if ( s[i] >= '0' && s[i] <= '9' ) { evaluare();}
else if ( s[i] == '(' ) sto.push( '(' );
else if ( s[i] == ')' ) {
while ( !sto.empty() && sto.top() != '(' )
calcul();
sto.pop();
}
else {
while( !sto.empty() && p[ s[i] ] <= p[sto.top()] )
calcul();
sto.push( s[i] );
}
}
while ( !sto.empty() )
calcul();
g << st.top();
return 0;
}