I have this assignment to make an infix calculator I think I have all the logical things figured out, but I am having trouble converting values. the return is a double, but the read in is a string and outputting as a double, I know that there is the difference is 48 from ascii value but I can't find where to take off this difference, I have tried a few different things and when I do 1+1 I either get 43 or -5 as my outputs. gonna keep banging my head but any help would be greatly appreciated! thank you! here is 2 of the 3 functions that assign my two stacks, 1 for digits and 1 for operators. anyone see something I don't?
double InFixCalculator::evaluate(string infix)
{
stack<char> opStack;
stack<double> valStack;
double test = 0;
for (unsigned int x = 0 ; x < infix.length() ; x++)
{
switch(infix[x])
{
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' :
valStack.push(infix[x]);
break;
case '(' :
opStack.push(infix[x]);
break;
/*case ')':
// Append/pop operators from stack until an ( is on top
while(opStack.top() != '(')
{
postFix += opStack.top();
opStack.pop();
}//end while
opStack.pop(); // Remove the open (
break;*/
case '+':
case'-':
case '*':
case '/':
if(opStack.empty())
opStack.push(infix[x]);
else if (precedence(infix[x]) > precedence(opStack.top()))
{
opStack.push(infix[x]);
}
else
{
while(!opStack.empty() && precedence(infix[x] <= precedence(opStack.top())))
{ execute(opStack,valStack);
opStack.push(infix[x]); // Push new operator onto stack.
}//end while
}//end if
break;
case ')':
while(opStack.top() != '(')
{
execute(opStack, valStack);
opStack.pop();
break;
}//end while
}//end switch
}//end for
while (!opStack.empty())
{
test += opStack.top();
opStack.pop();
}//end while
return test ;
}//end evaluate
void InFixCalculator::execute(stack<char> &opStack, stack<double> &valStack)
{ //I used if statements instead of a switch case, i find them easier to follow
// and it prevents fanning of coding, please dont take any points off =)
const int ASCII_DIGIT_OFFSET = 48;
double operand2, operand1, result ;
char op; // declaring variables for operations decisions
operand2 = ((int)valStack.top() - ASCII_DIGIT_OFFSET);
valStack.pop();
operand1 = ((int)valStack.top()- ASCII_DIGIT_OFFSET);
valStack.pop();
//setting operands for the top 2 values on the Valstack
op = opStack.top();
opStack.pop();
//seting the type of operations for operand1 and operand 2 from opStack
if(op == '+')
{
result = operand1 + operand2 ;
}
if(op == '*')
{
result = operand1 * operand2 ;
}
if(op == '/')
{
if(operand2 == '0')
{
cout <<"Division by zero error!";//catching division by zero for error handling
}
else
{
result = operand1 / operand2 ;
}
}
if(op == '+')
{
result = operand1 + operand2 ;
}
if(op == '-')
{
result = operand1 - operand2 ;
}
valStack.push(result) ;// putting the result of top 2 operands onto the stack
}//end execute