2016-03-08 156 views
-4

几天前我开始学习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 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: "); 
     } 
    } 
} 

请不要太技术与你的答案,因为我还是很陌生以C和编程本身。

+1

您能更具体地了解您的预期功能与实际发生的情况吗? –

+1

亲爱的乔治,“*它不起作用*”是或多或少值得提供的错误描述。请更具体地说明什么是不行的,你得到了什么,你会期望得到什么。 – alk

+0

请学习使用调试器 – Minh

回答

1

您调用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, start)读取和忽略来自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; 
} 
1

你在这个代码错误是,你是比较字符*的东西(开始或结束)开始,它甚至没有启动。

因此,首先将输入值赋给* start,然后继续进行比较。

一个额外的提示是将您的“输入单词”放入一个小写字母,因为您将它与“开始”和“退出”进行比较,它们都是小写字母,如果您可以说“开始” “开始”。 检查ascii表来理解我在说什么。

相关问题