unary plus

This is a discussion on unary plus within the C++ Programming forums, part of the General Programming Boards category; I have rewritten bjarne stroustrup's calculator program to accept input from a file and parse it and evaluate it. Everything ...

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    1

    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.

  2. #2
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. unary operator overloading and classes
    By coletek in forum C++ Programming
    Replies: 9
    Last Post: 01-10-2009, 02:14 AM
  2. + unary operator
    By SourceCode in forum C Programming
    Replies: 0
    Last Post: 01-28-2005, 03:52 PM
  3. Problem with unary minus overloading
    By Strait in forum C++ Programming
    Replies: 7
    Last Post: 01-14-2005, 02:42 PM
  4. Overloaded Unary Operator ++
    By Jaymes76 in forum C++ Programming
    Replies: 6
    Last Post: 07-24-2003, 11:36 PM
  5. Unary + operator
    By yeskaran in forum C Programming
    Replies: 4
    Last Post: 07-08-2002, 11:27 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21