为什么 objective-c 语言中的循环 "scanf" 方法死圈?

Why the loop "scanf" method dead circle in objective-c lanuguage?

我在objective-c中写了一个小控制台程序。需要用scanf方法来接收number.When 我输入一个字符,它会生成一个mistake.So 我试着解决,但是却进入了一个死循环!看到下面的代码,帮我解决一下,非常感谢!

#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;
}

fflush 的文档指出:

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.

并且您正在尝试刷新 输入。试试 fpurge:

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

另外不要!scanf(...)。查看文档,这个函数 returns 是一个整数,不是布尔值,值可以是正数或负数(查看 EOF 的定义)。负值表示错误,但 ! 运算符将产生 false 并且您的代码不会要求新输入。

如果成功 scanf returns 成功解析的项目数,请检查。

所有这些功能的文档都可以通过 Xcode 或 man 命令获得。

HTH