unary plus

Printable View

• 11-19-2009
cengineer
unary plus
I have rewritten bjarne stroustrup's calculator program to accept input from a file and parse it and evaluate it. Everything works fine except for the instance where the plus sign acts as a signed value. For example 3*+2.5 equals 7.5 but the program expects a parenthesis. How can I implement the change?
Code:

```                  }           case MINUS :                        // unary minus                 return -prim(true);           case LP :           {                 double e = expr(true);                 if (curr_tok != RP) return error("')' expected");                 get_token();                        //eat ')'                 return e;           }```
This is what is applied when a unary minus is used but I cannot add a unary plus statement since it creates an error that plus is already used.
• 11-19-2009
nadroj
Once you read an operator, look to see if the next character is another operator (well, one of + -). If its a "+", ignore it. If its a "-", then multiply the operand it follows by -1 then continue as normal.

For example "1++2". Read the left operand "1". Read the operator "+" and check the next character for "+" or "-". Since its a "+", ignore it and continue normally. This is true because: 1 + 2 = 1 + (+2). If the input was "1+-2", the left operand again is "1", read the operator "+", and see that the following character is one of "+" or "-". So multiply the right operand by -1: (-1)*2=-2, and continue normally. So 1+-2 = 1 + (-1)*(2) = 1 + (-2) = 1 - 2.