Pagini recente » Cod sursa (job #2082514) | Cod sursa (job #2557495) | Cod sursa (job #2115808) | Cod sursa (job #960698) | Cod sursa (job #459827)
Cod sursa(job #459827)
#include <stack>
#include <string>
#include <cstdlib>
#include <fstream>
/*
*
*/
using namespace std;
string expresion, t;
inline int priority( char x )
{
if( '(' == x )
return 0;
if( '+' == x || '-' == x )
return 1;
if( '*' == x || '/' == x )
return 2;
if( ')' == x )
return 3;
return 5;
}
void transform( void )
{
int p;
stack< char > s;
string::const_iterator it=expresion.begin(), iend=expresion.end();
while( it < iend )
{
if( *it >= '0' && *it <= '9' )
{
for( ; it < iend && *it >= '0' && *it <= '9'; ++it )
t.push_back(*it);
t.push_back('\'');
}
else if( '(' == *it )
{
++it;
s.push('(');
}
else if( ')' == *it )
{
for( ++it; '(' != s.top(); s.pop() )
t.push_back( s.top() );
s.pop();
}
else {
for( p=priority( *it ); !s.empty() && p <= priority(s.top()); s.pop() )
t.push_back(s.top());
s.push(*it);
++it;
}
}
for( ; !s.empty(); s.pop() )
t.push_back(s.top());
}
int eval( void )
{
int n, a, b;
stack< int > s;
transform();
string::const_iterator it=t.begin(), iend=t.end();
for( ; it < iend; ++it )
{
if( *it >= '0' && *it <= '9' )
{
for( n=0; *it >= '0' && *it <= '9'; ++it )
n=n*10+*it-'0';
s.push(n);
}
else {
b=s.top(); s.pop();
a=s.top(); s.pop();
switch( *it )
{
case '+' : s.push(a+b); break;
case '-' : s.push(a-b); break;
case '*' : s.push(a*b); break;
case '/' : s.push(a/b); break;
}
}
}
return s.top();
}
int main( void )
{
ifstream in( "evaluare.in" );
getline( in, expresion, '\n' );
ofstream out( "evaluare.out" );
out<<eval()<<'\n';
return EXIT_SUCCESS;
}