Objective-C scanf spaces issue
- by Rob
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?