Although Loop with a nested switch in Objective-C

I just started learning Objective-C. I am doing one of the standard calculator exercises. It is supposed to create a machine for adding (for example, enter the operator and number, display the result each time). But I messed up something, and I think this is due to the use of the char data type.

Here is the code, just a section of the program (the interface and implementation are simple and work in a different version, but if someone wants to see them, just ask):

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
double      value1 = 0.0;
char        operator = 'a';

Calculator *deskCalc = [[Calculator alloc] init];

NSLog(@"Initial value?");
scanf("%lf",&value1);

[deskCalc setAccumulator: value1];

while (operator != 'e') {
    {
    NSLog(@"Operation and value?");
    scanf("%c %lf", &operator, &value1);
    }
    switch (operator){
        case '+':
            [deskCalc add: value1];
            NSLog(@"%f", [deskCalc accumulator]);
            break;
        case '-':
            [deskCalc subtract: value1];
            NSLog(@"%f", [deskCalc accumulator]);
            break;
        case '*':
        case 'x':
            [deskCalc multiply: value1];
            NSLog(@"%f", [deskCalc accumulator]);
            break;
        case '/':
            if (value1 != 0) {
                [deskCalc divide: value1];
                NSLog(@"%f", [deskCalc accumulator]);
            }
            else {
                NSLog(@"Division by zero not allowed.");
                NSLog(@"%f", [deskCalc accumulator]);                   
            }
            break;
        case 's': 
            [deskCalc setAccumulator: value1];
            NSLog(@"%f", [deskCalc accumulator]);
            break;
        case 'e':
            NSLog(@"Done, sucker, final answer: %f.", value1);
        default:
            NSLog(@"Unknown operator.");
            NSLog(@"%f", [deskCalc accumulator]);
            break;


}
}

    [deskCalc release];

[pool drain];
return 0;

}   

And, in case this helps, here is what I get from the terminal when I run this:

From terminal:

Initial value?

12 // My input

Operation and meaning?

x 4 // My input

Unknown operator.

Operation and value? // It does not stop to request input.

48.000000

Operation and meaning?

Help and thanks.

P.S. , . , , , Basic Coleco Adam, - , , .

+3
2
scanf(" %c %lf", &operator, &value1);

%c, , stdin.

+4

operator \n. , flushall().

0

All Articles