【问题标题】:Why is there no output from this y/n program为什么这个 y/n 程序没有输出
【发布时间】:2012-09-22 13:55:26
【问题描述】:

我遇到了一个小型 C 程序的问题。它输出一个问题(见下面的代码),我可以将其输入(y 和 n),但随后什么也没有发生,即使它是为了根据输入的输入(y 或 n)打印一些东西。但是,在我的问题之后没有输出任何内容,程序就退出了。代码如下:

#include <stdio.h>

int main()
{
        char string [80];
        static char y;
        static char n;
        printf( "ARE YOU SHAQIRI? [y/n]: " );
        scanf( "%s", string );
        if ("%s" == "y")
                printf("That's impossible. YOU CANNOT BE SHAQIRI YOU IDIOT");
        else if ("%s" == "n")
              printf("I thought not.");
        fflush ( stdin );
        return 0;
}

【问题讨论】:

  • 当 y/n 响应只需要一个字符时,为什么要浪费 80 字节的字符串呢?只需getchar() 而不是scanf()
  • 永远不要在 stdin 上调用 fflush - 这会导致未定义的行为。另外,你为什么要让你的局部变量static
  • 这是根本错误:"%s" 并不神奇。它只是带有百分号和 s 的文字字符串。所以 "%s" == "y" 将永远为假,"%s" == "n" 也是如此。

标签: c string conditional stdin


【解决方案1】:

你的比较有两个问题:if ("%s" == "y"):

  • "%s" 是您的 scanf 格式字符串。如果scanf 成功读取输入,则结果在您的变量中:string
  • 不要使用== 来比较字符串。你应该使用strcmp

因为您在两个if 测试中都使用了这种形式的比较,所以两个分支都不执行,并且您看不到任何输出。

也不要在stdin 上致电fflush。你可能打算在那里fflush(stdout)

【讨论】:

  • 好的,所以在从这里修改程序并使用 Mike 的示例之后,链接器抛出了一个心理错误 - pastebin.com/QA3eFHiR
  • 好的,所以我的大错误变成了一个小错误(我需要包含 stdlib.h 和 string.h :) shaqiri.c:10:13: error: expected ‘)’ before string constant shaqiri.c:12:18: error: expected ‘)’ before string constant
  • @islandmonkey 看看你的strcmp 电话:(strcmp "input", n)。你有问题:1)不是一个有效的函数调用; 2) 裸露的n 不是变量或字符串。你不想要"n"吗?
【解决方案2】:

这不是你在 C 中比较字符串的方式,你需要使用strcmp。另外,您需要比较变量string,而不是"%s"

【讨论】:

    【解决方案3】:

    scanf() 将返回值存储在第二个参数中。见here。其次,您正在错误地比较字符串...使用strcmp

    我只是想把它扔出去,以简化你的程序:

    1. 使用单个字符存储单个字符输入
    2. 您可以按照您现在想要的方式保留条件“==”
    3. 删除了标准输入的 fflush,你不应该这样做。
    4. 为非 'y'/'n' 输入值添加了“catch all”案例。

    这是修改后的代码:

    #include <stdio.h>  
    int main() {
        char input;
        printf( "ARE YOU SHAQIRI? [y/n]: " );
        input = getchar();
        if (input == 'y')
            printf("That's impossible. YOU CANNOT BE SHAQIRI YOU IDIOT");
        else if (input == 'n')
            printf("I thought not.");
        else
            printf("Not valid input...");
        return 0; 
    } 
    

    【讨论】:

      【解决方案4】:

      C 没有用于比较 char 数组的内置运算符,因此您调用 strcmp,如下所示:

      if(strcmp(string, "yes") == ) 
      {
          /* User said yes */
      }
      

      请务必#include &lt;string.h&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-05
        • 2023-04-09
        • 1970-01-01
        • 2021-04-04
        • 1970-01-01
        相关资源
        最近更新 更多