我无法弄清楚为什么这段代码直接跳到模式5.我已经好几次看了它,我只是看不到它。任何帮助将不胜感激。我猜这与我初始化数组的方式和我比较它们的方式有关。我曾尝试使用'strcmp'并且目前正在尝试比较直接阵列位置。这两个都已成功编译,但我似乎无法让它工作。
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 :(得分: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);
}
do-while
循环,因为i
仅增加了for
外i
循环。由于if else
在do-while内没有增加
会导致无限循环。strcmp()
等同条件替换string.h
条件
并在文件中包含 for (int i = 0; i < 2; i++)
。如果您希望它显示所有3个结果,请更改:
for (int i = 0; i <= 2; i++)
要
i < 2
目前,对于i = {0, 1}
,i = 2
会为i <= 2
循环,并在条件失败时跳过i = {0, 1, 2}
。如果您将条件更改为{{1}},则会循环{{1}}。