Pagini recente » Cod sursa (job #3309686) | Cod sursa (job #1017897) | Cod sursa (job #2748426) | Cod sursa (job #3308407) | Cod sursa (job #672359)
Cod sursa(job #672359)
#include <stack>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
inline int priority( char op )
{
switch( op )
{
case '(' : return -5;
case '+' : ;
case '-' : return 1;
case '*' : ;
case '/' : return 2;
default : return 5;
}
}
string transform( string expresion )
{
int p;
string t;
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 )
{
++it;
for( ; '(' != s.top(); t.push_back(s.top()), s.pop() );
s.pop();
}
else {
p=priority(*it);
for( ; !s.empty() && p <= priority(s.top()); t.push_back(s.top()), s.pop() );
s.push( *it );
++it;
}
}
for( ; !s.empty(); t.push_back(s.top()), s.pop() );
return t;
}
int eval( string expresion )
{
int x, a, b;
stack< int > s;
string::const_iterator it, iend;
expresion=transform( expresion );
for( it=expresion.begin(), iend=expresion.end(); it < iend; ++it )
{
if( *it >= '0' && *it <= '9' )
{
for( x=0 ; it < iend && *it >= '0' && *it <= '9'; ++it )
x=x*10+*it-'0';
s.push(x);
}
else {
x=priority(*it);
if( x >= 1 && x <= 2 )
{
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);
}
}
}
}
return s.top();
}
int main()
{
string exp;
ifstream in( "evaluare.in" );
getline( in, exp );
ofstream out( "evaluare.out" );
out<<eval(exp)<<'\n';
return EXIT_SUCCESS;
}