2015-02-23 40 views
0

我無法弄清楚爲什麼這段代碼直接跳到了模式5.我已經看了好幾遍,而我只是沒有看到它。任何幫助將不勝感激。我猜測它與我初始化數組的方式以及我比較它們的方式有關。我曾嘗試使用'strcmp',目前正試圖比較直接陣列位置。這兩個都編譯成功,但我似乎無法讓它工作。C編程 - 將常量字符數組與用戶輸入進行比較

char one[3][3]; 
    const char *pattern[] = {"p1","p2","p3","p4","p5"}; 

    printf("%s Commands are {'p1', 'p2', 'p3', 'p4', 'p5'\n", prompt); 
    printf("Enter your first pattern choice: "); 
    scanf("%2s",one[0]); 

    printf("Enter your second pattern choice: "); 
    scanf("%2s",one[1]); 

    printf("Enter your third choice: "); 
    scanf("%2s",one[2]); 

    for (int i = 0; i < 2; i++) 
    { 
     do{ 
      if (one[i] == "p1") 
      { 
       printf("\n1.1"); 
       patternOne();} 
     else if (one[i] == "p2") 
      { 
       printf("\n1.2"); 
       patternTwo();} 
     else if (one[i] == "p3") 
      { 
       printf("\n1.3"); 
       patternThree();} 
     else if (one[i] == "p4") 
      { 
       printf("\n1.4"); 
       patternFour();} 
     else 
      { 
       printf("\n1.5"); 
       patternFive(); 
     } 

    } 
while (i < 3); 
+0

你不知道如何比較字符串。查找'strcmp()'(然後刪除這個問題) – John3136 2015-02-23 03:17:53

回答

1

對於字符串比較使用strcmp()功能從string.h

您沒有比較C風格的字符串,因此它正在評估爲else

你預期的代碼可能會是:

#include <stdio.h> 
#include <string.h> 

int main(int argc, char *argv[]) 
{ 
    char one[3][3]; 
    const char *pattern[] = { "p1", "p2", "p3", "p4", "p5" }; 

    printf("Enter your first pattern choice: "); 
    scanf("%2s", one[0]); 

    printf("Enter your second pattern choice: "); 
    scanf("%2s", one[1]); 

    printf("Enter your third choice: "); 
    scanf("%2s", one[2]); 

    for (int i = 0; i < 2; i++) 
    { 
     if (strcmp(one[i],"p1") == 0) 
     { 
      printf("\n1.1"); 
      patternOne(); 
     } 
     else if (strcmp(one[i], "p2") == 0) 
     { 
      printf("\n1.2"); 
      patternTwo(); 
     } 
     else if (strcmp(one[i], "p3") == 0) 
     { 
      printf("\n1.3"); 
      patternThree(); 
     } 
     else if (strcmp(one[i], "p4") == 0) 
     { 
      printf("\n1.4"); 
      patternFour(); 
     } 
     else if (strcmp(one[i], "p5") == 0) 
     { 
      printf("\n1.5"); 
      patternFive(); 
     } 
     else 
     { 
      printf("Unknown input."); 
     } 
    } 
    return(0); 
} 

所做的更改:

  1. 刪除內do-while環路i由 外for僅環遞增。由於i在do內部不會增加,而 會導致無限循環。
  2. 添加了一個else if處理p5輸入,並添加了一個單獨的else 來指示遇到了不期望的輸出。
  3. 代替if else條件與strcmp()等價條件 和包括string.h在文件中。

編輯(回答評論):

如果你希望它顯示所有3個結果,改變:

for (int i = 0; i < 2; i++) 

for (int i = 0; i <= 2; i++) 

目前,i < 2它當條件失敗時,循環爲i = {0, 1}並跳過i = 2。如果您將條件更改爲i <= 2,則它將循環顯示i = {0, 1, 2}

+0

真棒迴應謝謝!那就是訣竅。現在雖然它只顯示輸入的任何3種模式中的2種。任何線索,爲什麼這是? – Charkins12 2015-02-23 03:40:34

相關問題