Pagini recente » Cod sursa (job #1150436) | Cod sursa (job #460417) | Cod sursa (job #1601067) | Cod sursa (job #2830484) | Cod sursa (job #434593)
Cod sursa(job #434593)
/*
* File: main.cpp
* Author: VirtualDemon
*
* Created on April 6, 2010, 8:49 AM
*/
#include <stack>
#include <sstream>
#include <cstdlib>
#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 transform;
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 )
transform<<*it;
transform<<' ';
continue;
}
if( '(' == *it )
{++it;
v.push('(');
continue;
}
if( ')' == *it )
{
for( ++it; '(' != v.top(); v.pop() )
transform<<v.top();
v.pop();
continue;
}
p=priority( *it );
for( ; !v.empty() && p <= priority( v.top() ); v.pop() )
transform<<v.top();
v.push(*it);
++it;
}
for( ; !v.empty(); transform<<v.top(), v.pop() );
return transform.str();
}
inline int evaluate( string* expresion )
{
stack< int > v;
int number, a, b;
*expresion=transform( expresion );
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';
v.push(number);
continue;
}
b=v.top(); v.pop();
a=v.top(); v.pop();
switch( *it )
{
case '+' : v.push(a+b); break;
case '-' : v.push(a-b); break;
case '*' : v.push(a*b); break;
case '/' : v.push(a/b); break;
}
}
return v.top();
}
int main(int argc, char** argv)
{
string expresion;
ifstream in( "evaluare.in" );
getline( in, expresion );
ofstream out( "evaluare.out" );
out<<evaluate( &expresion )<<'\n';
return EXIT_SUCCESS;
}