2015-02-23 74 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

相关问题