Click here to Skip to main content
15,393,377 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
the title may sound confusing(I don't know a better way of phrasing it)

but I've got a calculator and I realized a big error in it , it cant accept '-' as it belives they are negative numbers: snippet of the space adding regex:
regex qret("ATAN|SIN|ACOS|LOG|ASIN|sqrt|CIR|sin|TAN|!|e|ln|EE|\\^|[^-?0-9a-z]",regex_constants::icase);

name = regex_replace( name, qret, " $& " ) ;
any way to not have -5-5 turn into -5 -5? instead -5 - 5?

What I have tried:

I've tried removing -? but it just disallowed negative numbers and allowed the statement, not very practical.
Updated 19-Jan-22 5:08am
Rick York 18-Jan-22 17:38pm
In C the binding of the minus sign with the value versus considering it an operation is a matter of precedence. That means you have to either implement precedence in your calculator or do something like require spaces to separate the values and operators.

I don't consider this a solution because I can't tell you how to implement precedence.
Luc Pattyn 18-Jan-22 18:14pm
I've never encountered a regex in the implementation of a calculator.
The typical approach is:
1. turn the input into RPN (reverse Polish notation)
2. evaluate what you have using a stack, where you either immediately execute an operator or push it onto the stack depending on precedence.

Obviously step 1 is to be skipped if you are mimicking an RPN calculator (such as HP35).
Abdulrahmon Tijani 18-Jan-22 18:39pm
@lucpattyn i do turn it in to rpn and do the precedences, i just need to give the expression spaces i order to tokenize the string
Luc Pattyn 18-Jan-22 20:11pm
if your tokenizer needs spaces, I'd suggest not to care about monadic minus. Simply threat a monadic minus as any other (dyadic) operator, so let it turn "-5" into "- SP 5" the same way it turns "+5" into "+ SP 5".

During the evaluation when you are expecting an operand and you get a minus sign, you only then must realize it is a monadic minus, not a dyadic minus, and act accordingly.

1 solution

This ambiguity is the reason many calculators have a - key for subtraction and a +/- key for changing a number's sign. If a number is currently displayed and + or - is entered, how do you know whether it should be a binary (addition or subtraction) or unary (change sign) operation? You could expect the user to put parentheses around a number when a unary operation is intended. But that's not very user friendly, because it's too late once a result is already on the display and you then want to change its sign.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900