Objective-C scanf spaces issue

Posted by Rob on Stack Overflow See other posts from Stack Overflow or by Rob
Published on 2010-05-03T04:30:05Z Indexed on 2010/05/03 4:38 UTC
Read the original article Hit count: 435

Filed under:
|
|

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)
                    NSLog(@"You can't divide by zero.");
                else 
                    [deskCalc divide: number];
                    NSLog (@"%lf", [deskCalc accumulator]);
                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?

© Stack Overflow or respective owner

Related posts about objective

Related posts about c