【问题标题】:else-if only giving out the if answerelse-if 只给出 if 答案
【发布时间】:2020-05-24 18:54:37
【问题描述】:

我正在为我的计算机科学课程做一个项目。我们要做一个文字冒险游戏。除了最后的循环之外,我几乎已经完成了所有工作。 if 语句工作正常,但 else if 语句只给出了 if 语句的答案,而不是我为它编写的单独语句。我试过很多不同的方法来写这个,但老实说我看不出问题所在。我将包含整个代码,以防循环之外的某个地方出现问题。

#include <stdio.h>
int main() {
    char name[1024];
    char kname[1024];
    char response[1024];
    printf("Wanna play a game? First, I need your name.\n");
    scanf("%s", name);
    printf("Your name is %s, huh? I like it.\n", name);
    printf("Let's get started. You're in the woods. You come across a cat, now you need to name them.\n");
    scanf("%s", kname);
    printf("So, you decided to name them %s? Not what I would've picked, but it's not my pet.\n", kname);
    printf("You come across a plague doctor. Is that why you came into the woods, to get away from the sickness? Not exactly brave. Anyway, I digress. The plague doctor promises the impossible, tells you that he can and will make you immune with an elixir. Do you take it?\n");
    scanf("%s", response);
    if (response, "yes") {
        printf("You took it, huh? Not what I would've picked, but hey, you seem fine. Uh oh, you don't look so good. I...don't think that was a good idea. Well, there's nothing I can do for you now. Maybe restart the game and see if you can make a better decision. Until next time, old friend.");
    } else if (response, "no") {
        printf("Good choice. Come on, I think there's a town up ahead. I'd list off what the town's name was and all that can be found there, but it's currently 11:32 pm on a Saturday and our creator is halfway convinced that this entire program is a fever dream.");
    }
    return 0;
}

【问题讨论】:

  • 这里的问题是if (response, "yes") 不是检查响应是否等于是的正确方法。试试if (!strcmp(response,"res"))
  • if 语句中的逗号可能没有按照您的想法执行。请改用 strncmp() 之类的函数。 en.wikipedia.org/wiki/Comma_operator
  • 看到这个ideone.com/kfAY5T

标签: c string if-statement conditional-statements adventure


【解决方案1】:

if (response, "yes")else if (response, "no") 没有适当的条件测试来处理你想要用它做的事情 - 比较两个字符串并通过结果控制流程是否有等价物。

(response, "yes") 被评估为1,其中if 语句的条件将始终为真。因此,else if-statement 或此后的语句(如果有多个)将永远不会被执行。

使用strcmp() 比较两个字符串。

if (response, "yes") 更改为if (!strcmp(response,"yes")),将else if (response, "no") 更改为if else (!strcmp(response,"no")),一切都会好起来的。

不要忘记在#include &lt;string.h&gt; 中包含string.h 的标头以使用strcmp()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    相关资源
    最近更新 更多