【问题标题】:Enter key in a while loop在while循环中输入键
【发布时间】:2016-04-26 23:12:03
【问题描述】:
#include <stdlib.h>
#include <stdio.h>

int main () 
{
    char word[100];

    while (word != "hello") {

        system("clear");

        printf("\nSay hello to me : ");

        scanf(" %s", word);
    }

    printf("congrats, you made it !");

    return 0;
}

在这段代码中:如果我输入除了你好之外的任何内容,循环继续。但是,输入 ENTER 键不会再次循环,只会添加一行。

我在某处读到使用 getchar() 可能会有所帮助,但我对 C 开发有点陌生,我被困在这里寻找几个小时如何使它工作。

编辑 0:

已删除

while (word != "hello")
char word[100];
scanf(" %s", word);

添加

#include <string.h>
while (strcmp(word, "hello") != 0)
char word[100] = {0}; 
fgets(word, 6, stdin);

编辑 1:

我试图在我的代码中包含类似的东西

fgets(word, 6, NULL);

但这让我遇到了分段错误。

**编辑2:**

正确的工作输入是:

fgets(word, 6, stdin);

所以它起作用了,但是在问题中添加了超过 6 个字符,例如:

Say hello to me : hello from the inside

只会打印:

Say hello to me :
Say hello to me :

所以我只是这样修改了函数:

fgets(word, 100, stdin);

但现在它不会让我有任何投入工作

【问题讨论】:

  • 又是一行一行的样式 :) ……不知道这么丑是哪来的?
  • 这段代码似乎没有将任何内容放入“word”中。您的 scanf 不应该使用 word 而不是 mot 吗?而且 mot 也没有定义。
  • 您正在与word != "hello" 进行指针比较,这保证为假。你想要的是strcmp(word, "hello") != 0
  • 请不要修改问题以应用任何建议的更改,因为这会使答案无效。相反,请评论更改是否有效。
  • 关于“输入ENTER键不会再次循环”,不要使用scanf(" %s",...。答案解释了“%s 格式说明符已经忽略了前导空格。”而是使用fgets()

标签: c enter getchar


【解决方案1】:

三件事:

scanf 格式字符串中不需要空格。 %s 格式说明符已经忽略了前导空格。所以不要使用" %s",而是使用"%s"

主要问题是word != "hello"。这不是比较字符串的方式。您实际上正在做的是将word 的地址与字符串常量"hello" 的地址进行比较。要进行字符串比较,请使用strcmp。如果返回 0,则字符串相同,因此您的 while 循环应检查非零:

while (strcmp(word,"hello")) {

一定要#include &lt;string.h&gt;获取strcmp的声明。

最后,您需要初始化word,以便初始字符串比较不会通过读取未初始化的数据来调用未定义的行为:

char word[100] = {0};

【讨论】:

  • scanf 是个坏主意,对于交互式会话,您想读取一行。
  • 记笔记谢谢。我实际上是在急于解决那个输入键问题,所以我忘记了我所有的礼仪:)
【解决方案2】:

@dbush 很好地回答了 OP 最初的担忧。

OP 现在使用fgets(word, 100, stdin); 并输入 h e l l o 输入。然后word[]"hello\n" 填充,这不会通过strcmp(word, "hello") != 0

解决方案:去掉最后的'\n'

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 100

int main() {
  char word[BUFFER_SIZE] = { 0 };

  while (strcmp(word, "hello") != 0) {
    system("clear");
    printf("\nSay hello to me : ");
    // insure buffered output is flushed
    fflush(stdout);

    // Avoid magic numbers, use `sizeof  word`
    // Test if input was received
    if (fgets(word, sizeof word, stdin) == NULL) {
      fprintf(stderr, "\nInput closed\n");
      return 1;
    }

    // lop off potential trailing \n
    word[strcspn(word, "\n")] = '\0';
  }

  printf("congrats, you made it !\n");
  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-27
    • 2013-11-16
    • 2020-02-15
    • 2015-12-11
    • 2018-03-23
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多