繁体   English   中英

简单的 C 程序不返回任何输出

[英]Simple C program returns no output

我编写了一个简单的 C 程序,它接受用户输入并将其存储在 dataofUser 变量中,然后它允许用户选择是否要通过说是或否来显示他们输入的数据,这是通过 fgets 和 if 语句完成的检查 userChoice 变量是否在其中存储了 yes 或 no 取决于它是或否,它将显示数据或显示“无输出!”,当我运行程序时,我没有得到我在下面输入的数据的输出,你可以看到控制台上显示的内容:

Please enter your input: this is a random input
Your data has been entered please enter Yes or No to display it: yes

Process returned 0 (0x0)    execution time : 4.829 s
Press ENTER to continue.

这是构建消息日志和各种错误消息

||=== Build: Debug in randopoint2 (compiler: GNU GCC Compiler) ===|
/home/Documents/randopoint2/randopoint2/main.c||In function ‘main’:|
/home/Documents/randopoint2/randopoint2/main.c|17|warning: comparison between pointer and integer|
/home/Documents/randopoint2/randopoint2/main.c|17|warning: comparison with string literal results in unspecified behavior [-Waddress]|
/home/Documents/randopoint2/randopoint2/main.c|21|warning: comparison between pointer and integer|
/home/Documents/randopoint2/randopoint2/main.c|21|warning: comparison with string literal results in unspecified behavior [-Waddress]|
||=== Build finished: 0 error(s), 4 warning(s) (0 minute(s), 0 second(s)) ===|
||=== Run: Debug in randopoint2 (compiler: GNU GCC Compiler) ===|

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char dataOfUser[50];
   char userChoice[50];

  printf("Please enter your input: ");
  fgets(dataOfUser, 50, stdin);

  printf("Your data has been entered please enter Yes or No to dipslay it: ");
  fgets(userChoice, 50, stdin);


  if(userChoice[50] == "yes")
  {
  printf("Your notes are: %s", dataOfUser);
  }
  else if(userChoice[50] == "no")
  {
  printf("no output!");
  }

    return 0;
}

问题:

if(userChoice[50] == "yes")

这不是在 C 中比较字符串的方式。

此外,访问userChoice[50]是未定义的行为,因为您试图访问数组超出其范围。

else if(userChoice[50] == "no")

另请注意,当您按 Enter 结束输入时,换行符\\n存储在userChoice

解决方案:

  1. 添加#include <string.h>以获取strcmp函数。

  2. if(userChoice[50] == "yes")更改为if (strcmp(userChoice, "yes\\n") == 0)

  3. else if(userChoice[50] == "no")改为else if (strcmp(userChoice, "no\\n") == 0)

在旁边:

printf("Your data has been entered please enter Yes or No to dipslay it: ");

您要求用户输入“是”或“否”,但将其与代码中的“是”和“否”进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM