to get negative number from cin.peek() funtion

Hi,

I'm having this problem.

Scenario:
The user enters a prefix form of numbers and I have to send back the result with postfix form. The result is ok but negative number. When the user enters a negative value, my code doesn't read it as a sign(-) and instead, it reads it as an operator.

Here's my code.
1
2
3
4
5
6
7
8
9
10
11
if (isdigit(in.peek() ) || (in.peek() == DECIMAL) ) {
            in >> number;	
			cout << number << " ";
			numbers.push(number);
	}

//Check whether the input is correct operator or not
else if (strchr("+-*/", in.peek() ) != NULL) {  
            in >> symbol;
            operators.push(symbol); 
	}


I know C++ functions do they're supposed to do but to change my code :( I don't have yet such knowledge. Can you help me what should I change so that my program can accept negative numbers ?

thanks in advance
Ah, I understand.

The problem is how you are thinking about it. A minus sign is always an operator. Yep. Always.

Between two numbers it is a binary operator:

12 - 5


But when only prefixing a number, it is a unary operator:

- 5
12 + - 5

(which is the same as 0 - 5 and 12 + (0 - 5).)

So, the question becomes, "how do I know the difference?"


The way to tell is by knowing what kind of thing you expect to read next: is it a number or an operator? If you are expecting an operator and you get a minus sign, then it is a binary operator. If you are expecting a number and you find a minus sign, then it is a unary operator. You can always know what to expect next:

12 - 5
↑ ↑ ↑
│ │ number
│ operator
number

It is always 'number, operator, number', in that order. A 'number' may itself be a more complex expression...

Here's a good page on parsing mathematical expressions using recursive-descent: http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm
I don't know how extensive your homework assignment is, but this probably goes a little deeper than you need. It is the principle that is important as you implement your expression parser.

Hope this helps.
Last edited on
Wow, yes, you got what I want to mean and exactly what you say, are correct.

The problem is like that: -3+-3 = -6


Actually, this is bonus part of my school assignment. I'm really appreciate your help and now I'm reading some parts of the page you suggested. I hope it'd help me to solve my case.

hope someone can advise me more !

-3 + -3 = -6 Becomes 0 - 3 + 0 - 3 = -6
Topic archived. No new replies allowed.