#include <iostream>
#include <string>
using namespace std;
class PStack
{
public:
PStack();
void parse( char* expression );
bool isoper( std::string str );
bool isfloat( char* );
void push( double val );
void docalc( std::string oper );
double gettop();
private:
double Stk[100];
double *It;
int opers_num;
const char** valid_opers;// = { "+", "-", "*", "/", "^" };
};
bool PStack::isfloat( char* str )
{
char* ch = str;
do
{
if( *ch != '.' )
{
if( *ch > '9' || *ch < '0')
{
return false;
}
}
} while ( *(++ch) );
return true;
}
bool PStack::isoper( std::string str )
{
for(int i = 0; i < 5; i++)
{
if( str == valid_opers[i] )
{
return true;
}
}
return false;
}
void PStack::parse( char* expression )
{
char* pch = strtok(expression, " ");
do
{
if( !isoper( pch ) )
{
if( isfloat( pch ) )
{
this->push(atof(pch));
}
else
{
printf( "ERROR TYPE\n" );
return;
}
}
else
{
this->docalc( pch );
}
} while (pch = strtok( NULL, " "));
}
PStack::PStack()
{
It = Stk;
opers_num = 5;
valid_opers = (const char**)malloc( sizeof( char* ) * opers_num);
valid_opers[0] = "+";
valid_opers[1] = "-";
valid_opers[2] = "*";
valid_opers[3] = "/";
valid_opers[4] = "^";
}
void PStack::push( double val )
{
*It++ = val;
}
void PStack::docalc( std::string oper )
{
if( It - 2 >= Stk)
{
double vals[2] = {*(It-2), *(It-1)};
It -= 2;
if( oper == "+" )
{
this->push( vals[0] + vals[1] );
}
else if (oper == "-")
{
this->push( vals[0] - vals[1] );
}
else if (oper == "*")
{
this->push( vals[0] * vals[1] );
}
else if (oper == "/")
{
this->push( vals[0] / vals[1] );
}
else if (oper == "^")
{
this->push( pow(vals[0], vals[1]) );
}
}
}
double PStack::gettop()
{
return *( It - 1 );
return 0;
}
int main()
{
PStack ps;
char ch[] = "1.0 2.0 1.0 + + 2.0 *";
ps.parse(ch);
printf("%f", ps.gettop());
getchar();
}
Comments