【问题标题】:Scanf in Objective C Crashes Xcode And the ProgramObjective C 中的 Scanf 使 Xcode 和程序崩溃
【发布时间】:2013-10-10 01:53:14
【问题描述】:

我已经从代码中删除了 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;
}

【问题讨论】:

  • 你告诉 XCode 你正在构建一个“命令行应用程序”,对吧?
  • 我有。无论如何,在应用程序选项卡下的命令行工具。我已经吸取了教训。 =)
  • 我启动了 xcode 并粘贴了您的代码,它对我有用。 MacBook。一定是你的环境。抱歉,我无法提供更多帮助。
  • Xcode 真的崩溃了吗? Xcode 只是简单的报告程序以-1 的代码退出并不意味着 Xcode 崩溃了。
  • 对不起,你是对的。 XCode 本身不会崩溃,但程序会发生并且不再继续出现该错误。我是认真编程的新手,我的术语似乎不太准确。 -1 的代码是什么意思?我已经从里面搜索了 bejesus,但找不到发生了什么。

标签: objective-c c xcode crash scanf


【解决方案1】:
fflush(stdin);

你可能想要

fflush(stdout)

我不确定 fflush() 对打开输入的 FILE* 会做什么。 这可能是也可能不是您的问题的原因。

【讨论】:

  • 即使没有 fflush() 程序也会崩溃。我也无法在任何地方找到此错误代码。
【解决方案2】:

Return 和 Enter 键在 Xcode 中具有不同的含义。您进入产品菜单并选择构建构建以运行并在终端中执行它会正常工作。

在 Xcode 中,小键盘中的 Enter 键会以 -1 返回码停止程序。我不确定这是错误还是功能,但我在 Xcode 的键绑定中找不到键。

请查看here

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    相关资源
    最近更新 更多