MJ
BAN USERint EvaluateExpr(const std::string &postfix)
{
if (postfix.size()<1)
return 0;
std::array<char,4> oper={'+','-','*','/'};
std::stack<int> result;
for(auto ch:postfix)
{
auto ret= std::find_if(oper.cbegin(),oper.cend(),[ch](char ch1){ if (ch== ch1) return true;return false;});
if ( ret != oper.cend()) // so we find the operator
{
auto val1 = result.top();result.pop();
auto val2 = result.top();result.pop();
switch (ch)
{
case '+':result.push(val1+val2);
break;
case '-':result.push(val1-val2);
break;
case '*':result.push(val1*val2);
break;
case '%':result.push(val1/val2);
break;
default:
break;
}
}
else
{
int val = ch-'0';
result.push(val);
}
}
return result.top();
}
char *mstrtok(const char *str,const char *del)
{
static char *sp = NULL ;
static int pos = 0;
//this is the first time the function is getting called
if (sp == NULL)
{
if ((str == NULL) ||(del == NULL))
return NULL;
sp = new char[mstrlen(str)];
strcpy(sp,str);
}
//we have reached the end of string
if (sp[pos] == '\0')
return NULL;
int start = pos;
//find the delimiter
while (sp[pos]!='\0')
{
bool found = false;
for ( int i = 0 ; i < mstrlen(del);i++)
{
if (sp[pos]==del[i])
{
found = true;
break;
}
}
if (found)
{
sp[pos]='\0';
pos++;
return &sp[start];
}
pos++;
}
return &sp[start];
}
- MJ September 06, 2015