Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 提示用户输入时程序崩溃_C - Fatal编程技术网

C 提示用户输入时程序崩溃

C 提示用户输入时程序崩溃,c,C,我制作了一个简单的小程序,它在到达if语句部分之前崩溃了 #include <stdio.h> int main() { char name[100]; printf("What is your name?"); scanf("%s", name); printf("Hello, %s\n",name); printf("You are trapped in a tunnel. Go through the right doors to g

我制作了一个简单的小程序,它在到达if语句部分之前崩溃了

 #include <stdio.h>

int main()
{
    char name[100];
    printf("What is your name?");
    scanf("%s", name);
    printf("Hello, %s\n",name);
    printf("You are trapped in a tunnel. Go through the right doors to get out\n");

    int choice;

    printf("Choose door 1 or door 2");
    scanf("%d", choice);
    if (choice == 1){
        printf("This is the correct door");
    }

    else if (choice == 2){
        printf("This is the wrong door");
    }

    else{
        printf("Press 1 or 2");
    }

    return 0;
}
#包括
int main()
{
字符名[100];
printf(“你叫什么名字?”);
scanf(“%s”,名称);
printf(“你好,%s\n”,名称);
printf(“你被困在隧道里。穿过正确的门出去\n”);
智力选择;
printf(“选择门1或门2”);
scanf(“%d”,选择);
如果(选项==1){
printf(“这是正确的门”);
}
else if(选项==2){
printf(“这是错误的门”);
}
否则{
printf(“按1或2”);
}
返回0;
}
我的程序运行正常,没有错误,只是崩溃了…

scanf(“%d”,&choice)

这就是它的本意
choice
是一个独立的
int
,因此您需要将其地址传递给
scanf
,以获得正确的结果。您现在要做的是将存储在
choice
中的值传递给
scanf
,而它需要一个地址

C库函数
intscanf(constchar*format,…)
读取 来自标准输入的格式化输入

所以它应该是这样的:

int choice;

printf("Choose door 1 or door 2");
scanf("%d", &choice); //& means the address-of
if (choice == 1){
    printf("This is the correct door");
}

else if (choice == 2){
    printf("This is the wrong door");
}

else{
    printf("Press 1 or 2");
}

您在
scanf
语句中遗漏了
,这就是为什么它不起作用。。
应该是

scanf("%d",&choice);

scanf(“%d”,选项)应该是
scanf(“%d”和&choice)
您可能忘记启用格式字符串警告(例如,GCC中的
-Wformat
)。如果你的编译器不提供一个选项,认真考虑升级!如果使用,您应该启用所有警告和调试信息
gcc-Wall-Wextra-g
,并改进代码以不获取警告。。。然后您应该使用调试器
gdb
@BasileStarynkevitch或使用IDE;)IDE不是编译器。它只运行一个。因此,更好地了解如何运行编译器