I’m learning Objective-C and trying to make a very simple command line calculator.
‘S’ should set the calculator to a specific value and ‘E’ should end the calculator.
My solution for this was to create a while-loop and let it run while the operator is not equal to ‘E’ or ‘e’.
Problem: if the operator is equal to ‘E’ or ‘e’, the while-loop is still executed (because it returns the message ‘Please use a valid operator’).
(I also tried it with an do-while statement but that didn’t work either)
while (operator != 'E' && operator != 'e')
{
NSLog (@"Type in a number and an operator.");
scanf ("%lf %c", &number, &operator);
if (operator == 'S' || operator == 's')
{
[deskCalc setResult: number];
}
else if ( operator == '+' )
{
[deskCalc add: number];
}
else if ( operator == '-' )
{
[deskCalc subtract: number];
}
else
{
NSLog(@"Please use a valid operator ( + or - )");
}
}
if (operator == 'E' || operator == 'e')
{
[deskCalc showResult];
}
Why are the while-statements still being executed if I use ‘E’ as an operator?
operatorisn’t ‘E’ until you type it in – by that point, you are inside the loop, so the invalid operator message will be shown. You need to check again after yourscanfand break out of the loop if the value isEore.