Why 'exactly' does this code loop endlessly if you enter a non number character?
The first question comes about because I want to learn good defensive coding. Does anyone know a good way to check user input? My google-fu failed me. Some people seemed to be of the opinion that if I specify %f
in scanf
that I am 'demanding' a float
; I verified this, in a way, by printing the value of userInput
. In fact, if I comment out the do while
loop, there is 'no problem' with the execution of the code. It assigns a 0
to userInput
and goes about its business.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
float userInput;
float result;
NSLog(@"3X^3 -5x^2 + 6");
do {
NSLog(@"What is x?");
scanf("%f", &userInput);
NSLog(@"userInput = %f", userInput);
} while(userInput == 0);
result = 3 * (userInput * userInput * userInput) - 5 * (userInput * userInput) + 6;
NSLog(@"the result is: %f", result);
[pool drain];
return 0;
}