Pagini recente » Cod sursa (job #2339766) | Cod sursa (job #1286643) | Cod sursa (job #2591318) | Cod sursa (job #1404592) | Cod sursa (job #446372)
Cod sursa(job #446372)
/*
* File: main.cpp
* Author: virtualdemon
*
* Created on April 25, 2010, 6:43 PM
*/
#include <stack>
#include <string>
#include <cstdlib>
#include <fstream>
/*
*
*/
using namespace std;
string t, expresion;
string::const_iterator it, iend;
inline int priority( char op )
{
if( '(' == op )
return 0;
if( '+' == op || '-' == op )
return 1;
if( '*' == op || '/' == op )
return 2;
return 5;
}
inline void transform( void )
{
int p;
stack< char > s;
it=expresion.begin();
iend=expresion.end();
for( ; it < iend; )
{
if( *it >= '0' && *it <= '9' )
{
for( ; it < iend && *it >= '0' && *it <= '9'; ++it )
t.push_back(*it);
t.push_back('.');
continue;
}
if( '(' == *it )
{
s.push(*it);
++it;
continue;
}
if( ')' == *it )
{
for( ++it; '(' != s.top(); s.pop() )
t.push_back(s.top());
s.pop();
continue;
}
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() );
}
inline int eval( void )
{
stack< int > s;
int number, a, b;
transform();
for( it=t.begin(), iend=t.end(); it < iend; ++it )
{
if( *it >= '0' && *it <= '9' )
{
for( number=0; *it >= '0' && *it <= '9'; ++it )
number=number*10+*it-'0';
s.push(number);
continue;
}
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(int argc, char** argv)
{
ifstream in( "evaluare.in" );
ofstream out( "evaluare.out" );
getline( in, expresion );
out<<eval()<<'\n';
return (EXIT_SUCCESS);
}