【问题标题】:Simple C program returns no output简单的 C 程序不返回任何输出
【发布时间】:2020-04-02 17:12:17
【问题描述】:

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

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;
}

【问题讨论】:

  • 提示,userChoice[50] != "yes" userChoice[50] != "no"。你需要strcmp
  • 请退后一步,刷新关于如何比较字符串的教科书、课堂笔记或教程。并且一般使用数组。我还建议您阅读更多关于 fgets 以及它添加到缓冲区的内容。
  • @ElliottFrisch 哇,它有效,为什么它不适用于 ==?以及为什么要添加感叹号符号
  • userChoice[50] 首先是无效的,超过了数组的末尾。
  • 你说对了一部分。定义变量时,括号中的数字定义数组的大小。但是当你访问元素时,它是单个元素的索引。 array[50] 包含元素 array[0]..array[49]

标签: c pointers fgets strcmp


【解决方案1】:

问题:

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

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

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

else if(userChoice[50] == "no") 也是如此

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

解决方案:

  1. 添加#include &lt;string.h&gt;得到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: ");

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

【讨论】:

  • 数组的访问越界是什么意思?
  • @Qasim 这是你的数组:char dataOfUser[50];。它可以存储多少个字符? 50. 你如何访问它的元素? dataOfUser[0](第一个元素)、dataOfUser[1](第二个元素)等等。那么如何访问第 50 个元素呢? dataOfUser[49](第 50 个元素)。现在想想dataOfUser[50],您正在尝试访问数组之外​​的元素!
猜你喜欢
  • 1970-01-01
  • 2016-02-13
  • 1970-01-01
  • 2012-04-04
  • 2015-11-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
  • 1970-01-01
相关资源
最近更新 更多