C 为什么这会给我一个逻辑错误?
我几天前开始学习C语言,现在已经学习了基本知识,我正在尝试制作一个基于文本的小游戏 在完成此菜单功能后,我尝试运行我的应用程序,但由于某些原因,它无法运行:C 为什么这会给我一个逻辑错误?,c,C,我几天前开始学习C语言,现在已经学习了基本知识,我正在尝试制作一个基于文本的小游戏 在完成此菜单功能后,我尝试运行我的应用程序,但由于某些原因,它无法运行: #include <stdio.h> #include <stdlib.h> #include <string.h> int menu() { char *start; printf("Welcome to my game\n Type START to begin or EXIT to
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int menu() {
char *start;
printf("Welcome to my game\n Type START to begin or EXIT to quit: ");
while (strcmp(start, "start") != 0 && strcmp(start, "exit") != 0) {
scanf("%s", &start);
if (strcmp(start, "start") == 0) {
return 1;
} else
if (strcmp(start, "exit") == 0) {
return 0;
} else {
printf("Invalid command. Try again: ");
}
}
}
#包括
#包括
#包括
int菜单(){
字符*开始;
printf(“欢迎来到我的游戏\n键入开始开始或退出退出:”;
while(strcmp(start,“start”)!=0和strcmp(start,“exit”)!=0){
scanf(“%s”,开始(&s));
如果(strcmp(开始,“开始”)==0){
返回1;
}否则
如果(strcmp(开始,“退出”)==0){
返回0;
}否则{
printf(“无效命令。请重试:”;
}
}
}
请不要对你的答案太过技术化,因为我对C语言和编程本身还很不熟悉。你调用scanf(“%s”,…)
时,指针的地址指向char*
,这不是正确的类型,指针也没有初始化。您应该使start
成为一个数组,并通过以下方式调用scanf
:
char start[80];
if (scanf("%79s", start) == 1) {
/* word was read, check its value */
} else {
/* no word was read, probably at end of file */
}
scanf(“%79s,开始)
读取并忽略stdin
中的任何空白字符,然后将一个高达79字节的字读入start
指向的数组。如果没有79
,scanf
将无法判断何时停止,如果标准输入包含很长的字,则可能导致缓冲区溢出。这是一个攻击者可以利用使您的程序运行任意代码
以下是您的代码的修改版本:
#include <stdio.h>
#include <string.h>
int menu(void) {
char start[80];
printf("Welcome to my game\n Type START to begin or EXIT to quit: ");
for (;;) {
if (scanf("%79s", start) != 1) {
break;
if (strcmp(start, "start") == 0) {
return 1;
} else
if (strcmp(start, "exit") == 0) {
return 0;
} else {
printf("Invalid command. Try again: ");
}
}
printf("unexpected end of file\n");
return -1;
}
#包括
#包括
int菜单(无效){
字符开始[80];
printf(“欢迎来到我的游戏\n键入开始开始或退出退出:”;
对于(;;){
如果(扫描频率(“%79s”,开始)!=1){
打破
如果(strcmp(开始,“开始”)==0){
返回1;
}否则
如果(strcmp(开始,“退出”)==0){
返回0;
}否则{
printf(“无效命令。请重试:”;
}
}
printf(“意外的文件结尾\n”);
返回-1;
}
您在这段代码中的错误是,您将char*start与某个东西(start或exit)进行比较,而它甚至没有启动
因此,首先为*start指定一个输入值,然后继续比较
另外一个技巧是将“输入字”放在小写字母中,因为您将其与“开始”和“退出”进行比较,这两个字母都是小写字母,如果您让我们说“开始”而不是“开始”,则情况有所不同。
查看ascii表格以了解我所说的内容。您能否更具体地说明预期功能与实际发生的情况?亲爱的George,“它不起作用。”“是可以提供的或多或少值得一提的错误描述。请更具体地说明什么不起作用,您得到了什么,以及您希望得到什么。请学习使用调试程序编译emmit警告吗?(它们是否处于活动状态?)[256];。