infix to postfix negation

lady_krizzie's Avatar, Join Date: Sep 2012
Newbie Member
Hello there,
I am trying to make a calculator program. But I have a problem with the negative sign. I fixed the program to do expression of (0-5)+12 if I want 5 to be negative. But I want and I am expecting it to do something like -5+12 .Please help...Thank you in advance

EXAMPLE OUTPUT :
Code:
Enter an infix expression: 
infix: -5+12 
postfix:_5_-_12_+  //'_' this sign is a space , 
error: pop empty stack //so this is wrong
but if I do this:
Code:
Enter an infix expression: 
infix: 5+12 
postfix:5_12_+  //'_' this sign is a space
Answer: 17 //so I succeded here
also, I have a condition:
Code:
case '-': 
         if ((input_string == OPERATOR) || (input_string == '\0') && (input_string== '-'))   
            { 
            return (UNARY); //a minus sign followed by a an operator or null is a unary 
            } 
              
         else 
            { 
            return (OPERATOR); //a minus sign after a number or right parenthesis is a subtraction
            }

so that in converting infix to postfix
Code:
case UNARY:
			push1(input_string[i]);
			break;
and in evaluating a postfix I have in my main:

case '-':
else if ('-' == UNARY) // unary operator
{
//push2(pop2() * (0-1));
push2(pop2() * -1);
}
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Well it's OK to post odd segments of the code but really we can't solve it from that. You have to post the whole thing. The solution is probably to extend your definition of a number: where you are expecting 0-9, you must also expect a possible '-', and it is the context that will define whether that means subtract or minus. So -5+12 would see the - as negative rather than subtract, because at that point it is expecting a number. But 12+-5 would also see the - as a negative because it's already seen an operator so is now expecting a number. On the other hand 12-5 would see the - as subtract, because it is looking for an operator, and programmed correctly your program shouldn't be confused by 12--5 which would be interpreted as 12 minus (-5).
lady_krizzie like this
lady_krizzie's Avatar, Join Date: Sep 2012
Newbie Member
Thank you but I'm still confused, from your explanation does it mean that I will make negative as part of the operand? i.e. 1+ -12 , push the whole -12?
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Yes of course. -12: the - is an essential part of the number. It's what makes it a negative number.
lady_krizzie's Avatar, Join Date: Sep 2012
Newbie Member
Is it like this? I put it this way but it didn't work.

Code:
case '-':
			if (input_string[i-1]==' ') // there is a space before the negative part
			{
				return (OPERAND);
			}
			else
			{
				return (OPERATOR);
			}
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
No idea, can't solve it from fragmented sections of code.