C 提示用户输入时程序崩溃
我制作了一个简单的小程序,它在到达if语句部分之前崩溃了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
#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不是编译器。它只运行一个。因此,更好地了解如何运行编译器