Pagini recente » Cod sursa (job #2975434) | Cod sursa (job #2953734) | Cod sursa (job #2960715) | Cod sursa (job #2597506) | Cod sursa (job #492120)
Cod sursa(job #492120)
/*
* File: main.cpp
* Author: bitone
*
* Created on October 13, 2010, 2:34 PM
*/
#include <stack>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
/*
*
*/
string expresion;
inline int priority( char x )
{
if( '(' == x )
return -1;
if( '+' == x || '-' == x )
return 0;
if( '*' == x || '/' == x )
return 1;
if( '^' == x )
return 2;
return 4;
}
inline void transform( string& expresion )
{
int op;
string t;
stack< char > v;
string::const_iterator it=expresion.begin(), iend=expresion.end();
while( it < iend )
{
if( '0' <= *it && *it <= '9' )
{
for( ; it < iend && '0' <= *it && *it <= '9'; ++it )
t.push_back(*it);
t.push_back('/');
}
else if( '(' == *it )
v.push(*it), ++it;
else if( ')' == *it )
{
for( ++it; '(' != v.top(); t.push_back( v.top() ), v.pop() );
v.pop();
}
else {
for( op=priority(*it); !v.empty() && op <= priority(v.top()); t.push_back(v.top()), v.pop() );
v.push(*it);
++it;
}
}
for( ; !v.empty(); t.push_back(v.top()), v.pop() );
expresion=t;
}
inline int evaluate( void )
{
transform(expresion);
int number, a, b;
stack< int > v;
string::const_iterator it=expresion.begin(), iend=expresion.end();
for( ; it < iend; ++it )
{
if( '0' <= *it && *it <= '9' )
{
for( number=0; it < iend && '0' <= *it && *it <= '9'; ++it )
number=number*10+*it-'0';
v.push(number);
}
else {
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)
{
ifstream in( "evaluare.in" );
getline( in, expresion );
ofstream out( "evaluare.out" );
out<<evaluate()<<'\n';
return EXIT_SUCCESS;
}