objective-c - Objective C 中的 Scanf 导致 Xcode 和程序崩溃

标签 objective-c c xcode crash scanf

我已经从代码中删除了 scanf,程序的其余部分运行没有问题。当代码到达 scanf 并输入数字后,xcode“失去连接”并显示错误“程序以退出代码结束:-1”。我还尝试将“输入”设置为 int,更改变量输入的名称以防发生冲突,并尝试在代码中不使用 fflush。我在 Oracle VM Virtualbox 上运行 Mountain Lion,并且我的计算机运行的是 Windows 7(如果相关的话)。

我做错了什么?

#import Foundation/Foundation.h
#include stdio.h

int main(int argc, const char * argv[])

{

    @autoreleasepool {

        float input = 1;
        int i = 0;
        float total = 0;
        int max = 0;
        int min = 1000;


        while (input != 0){
            NSLog(@"Please put in a number. \n");
            scanf("%f", &input);

            fflush(stdin);

            if(input > max){
                max = input;
            }
            if(input < min){
                min = input;
            }
            total = total + input;
            i++;

        }

        printf("The number of entered numbers was %i \n", i);
        printf("The sum of the entered numbers is %f\n", total);
        total = total/i;
        printf("The average of all the numbers is %f\n", total);
        printf("The highest number entered is %i\n", max);
        printf("The lowest number entered is %i\n", min);


    }

    return 0;
}

最佳答案

fflush(stdin);

你可能想要

fflush(stdout)

我不确定 fflush() 会对打开输入的 FILE* 执行什么操作。 这可能是也可能不是导致您出现问题的原因。

关于objective-c - Objective C 中的 Scanf 导致 Xcode 和程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19285777/

相关文章:

ios - 控制 iPhone 中的扬声器

uint8_t 到字符串的转换 [C]

c - 如何使用 openssl 在 C 代码中进行相互 tls 身份验证?

swift - AR 对象在 RealityKit 中无法正确锚定或调整大小

iphone - 集成iOS6 facebook功能

iPhone 应用程序 : Webapps or native?

iphone - 从 iPhone 静态库中提取对象 (*.o) 文件

iphone - 来自 NSString 的 NSDate,如 HH :mm

c - 无效的读写valgrind

python - mac os 上的 cython 入门