Pagini recente » Cod sursa (job #573775) | Cod sursa (job #1711732) | Cod sursa (job #3216808) | Cod sursa (job #403425) | Cod sursa (job #434327)
Cod sursa(job #434327)
/*
* File: main.cpp
* Author: SpeeDemon
*
* Created on April 5, 2010, 4:50 PM
*/
#include <stack>
#include <sstream>
#include <fstream>
/*
*
*/
using namespace std;
inline int priority( char x )
{
if( '(' == x )
return 0;
if( '+' == x || '-' == x )
return 1;
if( '*' == x || '/' == x )
return 2;
return 5;
}
inline string transform( string* expresion )
{
int p;
stack< char > v;
ostringstream t;
string::const_iterator it=expresion->begin(), iend=expresion->end();
while( it < iend )
{
if( *it >= '0' && *it <= '9' )
{
for( ; *it >= '0' && *it <= '9' && it < iend; ++it )
t<<*it;
t<<' ';
continue;
}
if( '(' == *it )
{
v.push(*it), ++it;
continue;
}
if( ')' == *it )
{
++it;
while( '(' != v.top() )
t<<v.top(), v.pop();
v.pop();
continue;
}
p=priority( *it );
while( !v.empty() && p <= priority( v.top() ) )
t<<v.top(), v.pop();
v.push( *it );
++it;
}
while( !v.empty() )
t<<v.top(), v.pop();
return t.str();
}
inline int evaluate( string *expresion )
{
*expresion=transform( expresion );
stack< int > s;
int number, a, b;
string::const_iterator it=expresion->begin(), iend=expresion->end();
for( ; 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( void )
{
string expresion;
ifstream in( "evaluare.in" );
getline( in, expresion );
ofstream out( "evaluare.out" );
out<<evaluate( &expresion )<<'\n';
return EXIT_SUCCESS;
}