【问题标题】:strcmp does not stop when typing 'yes' command [closed]键入“是”命令时,strcmp 不会停止 [关闭]
【发布时间】:2016-04-11 17:34:08
【问题描述】:

我用字符串比较制作了这个笑话程序,但是当我输入“yes”时,它也会输入我对else 语句的内容。当我输入“no”时它不会这样做,如果我输入“yes”或“no”以外的其他内容,它会做出可预测的响应。

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

int main ()
{
    char ansr[50];
    printf("Are you a cop?");
    scanf("%s", &ansr);

    if (strcmp(ansr, "yes") == 0)
    {
        printf("Then get outta here buddy!");
    }

    if (strcmp(ansr, "no") == 0)
    {
        printf("Then you can learn the secret handshake!");
    }
    else 
        printf("\nDude! Yes or no question! Are you a cop?!\n");
}

【问题讨论】:

  • 用else if (strcmp(ansr, "no") == 0)替换if (strcmp(ansr, "no") == 0)
  • 我错过了您将“ansr”设置为什么的地方吗?
  • 缩进/格式化。接下来...
  • 您必须阅读用户输入,才能阅读用户输入。

标签: c strcmp


【解决方案1】:

有几点需要注意。首先,在使用 ansr 之前,您永远不会使用 scanf 将任何内容读入它,这会导致未定义的行为。其次,正如其他人所说,您的 if/else 陈述不一致。第三,如果答案无效,您需要一个while 循环来再次提问。你可以像这样重新排列它:

int main ()
{
    char ansr[50];
    printf("Are you a cop?\n");
    scanf("%49s", ansr);

    while (strcmp(ansr, "yes") && strcmp(ansr, "no"))
    {
        printf("\nDude! Yes or no question! Are you a cop?!\n");
        scanf("%49s", ansr);
    }

    if (strcmp(ansr, "yes") == 0)
    {
        printf("Then get outta here buddy!\n");
    }
    else
    {
        printf("Then you can learn the secret handshake!\n");
    }

    return 0;
}

【讨论】:

  • 如果在此处扫描,请告诉扫描仪限制:scanf ("%49s", ...。
  • 那么 do-while 循环呢?
  • @alk 谢谢,我修复了扫描。为什么要使用do-while?不明白你的意思。消息发生变化。
  • 这个只是循环第一个字符串无限
  • @thinksinbinary 它不会被循环中的 scanf 覆盖吗?我在发布之前确实测试了这段代码。
【解决方案2】:

ansr保持未初始化,在通过strcmp()接触它之前,后者调用了臭名昭著的未定义行为,任何事情都可能发生。

【讨论】:

    【解决方案3】:

    您的代码有一个 if 块和一个 if else 块。所以对比ansr两次,改成if else if block,只检查一次。

    #include<stdio.h>
    #include<string.h>
    
    int main ()
    {
    
    char ansr[50];
    printf("Are you a cop?");
    //should take input here
    if (strcmp(ansr, "yes") == 0)
    {
        printf("Then get outta here buddy!");
    }
    
    else if (strcmp(ansr, "no") == 0)
    {
       printf("Then you can learn the secret handshake!");
    }
    
    else printf("\nDude! Yes or no question! Are you a cop?!\n");
    
     return 0;
    }
    

    编辑:按照建议删除了一些单词。抱歉,从操作码中包含它们。

    【讨论】:

    • 缩进和格式,请顺便说一句:return statement
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多