-2

I write a small console program in objective-c. It need to use the scanf method to receive the number.When I enter a character, it will make a mistake.So I try to solve it,but it has entered a cycle of death! See the following code, to help me solve it, thank you very much!

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        int num1 = 0;
        NSLog(@"Please input number:");
        while (!scanf("%d", &num1)) {
            fflush(stdin);
            NSLog(@"Input error,just input number:");
        }
    }
    return 0;
}
fly_basket
  • 49
  • 7

1 Answers1

0

The documentation for fflush states:

The function fflush() forces a write of all buffered data for the given output or update stream via the stream's underlying write function. The open status of the stream is unaffected.

and you are trying to flush input. Try fpurge:

The function fpurge() erases any input or output buffered in the given stream.

Also do not write !scanf(...). Check the documentation, this function returns an integer, not a boolean, and the value could be positive or negative (look up the definition of EOF). A negative value indicates an error, but the ! operator will yield false and your code would not ask for new input.

If successful scanf returns the number of items successfully parsed, check for that.

The documentation for all these functions is available via Xcode or the man command.

HTH

CRD
  • 52,522
  • 5
  • 70
  • 86