2016-03-08 157 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表來理解我在說什麼。

相關問題