I figured I'd make one thread for things I fix / change, this was just the first significant change. If I understood what calc() was supposed to do in parser.cpp (that is, calculate a simple math expression in a string) then it had a few problems. I rewrote it, see below:
Code:
int calc( string calc )
{
string::iterator iterator = calc.begin();
string buffer;
string integer1;
char op = 0;
int returnvalue = 0;
while (*iterator)
{
char ch = *iterator;
if(ch >= '0' && ch <= '9')//If this character is numeric add it to the buffer
{
buffer += ch;
}
else if(ch == '+' || ch == '-' || ch == '/' || ch == '*')//otherwise, are we an operator?
{
int val = atoi(buffer.c_str());
if(!op)//if this is the first time through, set returnvalue to what we have so far
{
returnvalue = val;
}
else//otherwise we've got returnvalue initialized, perform operation on previous numbers
{
if(buffer.length() == 0)//Do we have a value?
{
printf("Parser::calc() Error in syntax: '%s'.\n", calc);
return 0;
}
//what was the previous op
switch(op)
{
case '+':
{
returnvalue += val;
break;
}
case '-':
{
returnvalue -= val;
break;
}
case '/':
{
if(val == 0)//can't divide by zero
{
printf("Parser::calc() Error, Divide by zero '%s'.\n", calc);
return 0;
}
returnvalue /= val;
break;
}
case '*':
{
returnvalue *= val;
break;
}
};
op = ch;//save current operator and continue parsing
buffer.clear();//clear buffer now that we're starting on a new number
}
op = ch;
}
else
{
printf("Parser::calc() Error processing '%c'.\n", ch);
return 0;
}
}
return returnvalue;
}