views:

263

answers:

1

I am learning objective-C and for the life of me can't figure out why this is happening. When the user inputs when the code is:

scanf("%c %lf", &operator, &number);

For some reason it messes with this code:

    doQuit = 0;
    [deskCalc setAccumulator: 0];
    while (doQuit == 0) {
        NSLog(@"Please input an operation and then a number:");
        scanf("%c %lf", &operator, &number);

        switch (operator) { 
            case '+':
                [deskCalc add: number];
                NSLog (@"%lf", [deskCalc accumulator]);
                break;
            case '-':
                [deskCalc subtract: number];
                NSLog (@"%lf", [deskCalc accumulator]);
                break;
            case '*':
            case 'x':
                [deskCalc multiply: number];
                NSLog (@"%lf", [deskCalc accumulator]);
                break;
            case '/':
            if (number != 0) 
                [deskCalc divide: number];
                NSLog (@"%lf", [deskCalc accumulator]);
            else 
                NSLog(@"You can't divide by zero.");
                break; 
            case 'S':
                [deskCalc setAccumulator: number];
                NSLog (@"%lf", [deskCalc accumulator]);
                break;
            case 'E':
                doQuit = 1;
                break;
            default:
                NSLog(@"You did not enter a valid operator.");
                break;
        }
    }

When the user inputs for example "E 10" it will exit the loop but it will also print "You did not enter a valid operator." When I change the code to:

scanf(" %c %lf", &operator, &number);

It all of a sudden doesn't print this last line. What is it about the space before %c that fixes this?

+2  A: 

White-space characters in the format string let scanf() read and ignore any whitespace character up to the next non-whitespace character. In your case this takes care of the newline characters that are left over from the previous input.

As for the / case, the indentation is misleading you - the statements in the if branch are not correct. If you want to have multiple statements there, you need to put them in one block using curly braces:

if (number != 0) {
    [deskCalc divide: number];
    NSLog (@"%lf", [deskCalc accumulator]);
} else {
    NSLog(@"You can't divide by zero.");
}

Note that the curly braces around the else branch are not needed here (it contains only one statement), but help readability.

Georg Fritzsche
I changed it above to try and fix the '/' method but now it wont even compile giving an error that says, "expected expression before 'else'"
Rob
@Rob: Updated the answer.
Georg Fritzsche
Great - that worked. Thanks for the help.
Rob