Pagini recente » Cod sursa (job #1102029) | Cod sursa (job #2290083) | Cod sursa (job #1565391) | Cod sursa (job #456504) | Cod sursa (job #543749)
Cod sursa(job #543749)
#include <stack>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
string expresion, t;
string::const_iterator it, iend;
inline int priorityOp( char op )
{
switch(op)
{
case '+' : ;
case '-' : return 1;
case '*' : ;
case '/' : return 2;
case ')' : return 3;
}
return -1;
}
inline void transform()
{
stack< char > s;
for( it=expresion.begin(), iend=expresion.end(); 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 )
s.push('('), ++it;
else if( ')' == *it )
{
for( ++it; '(' != s.top(); s.pop() )
t.push_back(s.top());
s.pop();
}
else {
for( int p=priorityOp(*it); !s.empty() && p <= priorityOp(s.top()); s.pop() )
t.push_back(s.top());
s.push(*it);
++it;
}
}
}
for( ; !s.empty(); s.pop() )
t.push_back(s.top());
}
inline int eval()
{
transform();
stack< int > s;
int number, a, b;
it=t.begin();
iend=t.end();
for( ; it < iend; ++it )
{
if( *it >= '0' && *it <= '9' )
{
for( number=0; it < iend && *it >= '0' && *it <= '9'; ++it )
number=number*10+*it-'0';
s.push(number);
}
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 );
ofstream out( "evaluare.out" );
out<<eval()<<'\n';
return EXIT_SUCCESS;
}