Questions about validating user input in Objective-C, number vs string

Why is this exact loop looping endlessly if you enter a character without a number?

The first question arises because I want to know good security coding. Does anyone know a good way to check user input? My google-fu failed me. Some people seem to be of the opinion that if I point %fin scanfthat I "demand" a float; I checked this, in a way, by typing a value userInput. In fact, if I comment on the loop do while, the code says "no problem." He appropriates from 0to userInputand goes about his 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;
}
+3
2

Objective-C Cocoa. C scanf . scanf, :

Zero , , , ; , % d.

scanf %f, , , , . , scanf float stdin. scanf, , userInput , , userInput 0.0 scanf stdin. .

userInput , , scanf while. scanf. , fpurge(stdin), , :

int rc = scanf("%f", &userInput);
if (rc == 0)
{
    NSLog(@"Invalid input, try again.");
    fpurge(stdin);
}

, C . , !

, Cocoa NSNumberFormatter .., , , , , .

+3

Cocoa NSFormatter, - NSNumberFormatter.

+1

Source: https://habr.com/ru/post/1728779/


All Articles