gpt4 book ai didi

C 编程 - 将 const char 数组与用户输入进行比较

转载 作者:行者123 更新时间:2023-11-30 15:23:43 24 4
gpt4 key购买 nike

我不明白为什么这段代码直接跳到模式 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);

最佳答案

对于字符串比较,请使用 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-while 中没有增加可能会导致无限循环。
  2. 添加了一个 else if cluse 来处理 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} .

关于C 编程 - 将 const char 数组与用户输入进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com