【问题标题】:How do I read in the Enter key as an input in C?如何读取 Enter 键作为 C 中的输入?
【发布时间】:2022-02-03 17:45:21
【问题描述】:

如何在 C 中将 Enter 键作为输入读取?我想要一些这样的程序:

"Please enter a key to go to next line"

如何在 C 中添加这种类型的选项?

我是编程新手。

【问题讨论】:

  • 请写代码好吗
  • 由于键盘输入在 C 中通常是行缓冲的,你可以直接写 getchar()
  • edit您的问题并告诉我们您使用的操作系统和编译器。当您在对答案的评论中写到编译器错误消息时,请显示您的代码和用于构建它的命令。 (显示minimal reproducible example。)

标签: c input stdin


【解决方案1】:

您可以使用stdio.h 中的getc 函数等待某个键被按下。此 C 代码将等待按下回车键然后输出“继续!”:

#include <stdio.h>

int main(){
    printf("Press any key to continue");
    getc(stdin);
    printf("Continued!");
    return 0;
}

【讨论】:

  • 但我找不到“任何”键!不过,说真的,你试过这个吗?它不适用于任何键,只需 Enter 键即可。
  • 此代码仅将输入键作为输入
  • @TapabrataGoswami 我弄错了,此代码仅适用于您需要的输入键
【解决方案2】:

如果我理解你的问题,你可以写:

printf("Press ENTER key to Continue\n");  
getchar();

或者

printf("Press Any Key to Continue\n");
getch();

【讨论】:

    【解决方案3】:

    只有另一个答案正确地触及了这一点。不要假设您的用户会服从您,即使他或她打算这样做。

    // Ask user to do something
    printf( "Press Enter to continue: " );
    fflush( stdout );
    
    // Wait for user to do it
    int c;
    do c = getchar();
    while ((c != EOF) and (c != '\n'));
    

    这会丢弃其他输入,直到按下 Enter 键或到达 EOF,使您的输入流处于已知状态。

    如果您希望有无缓冲的输入,那就是完全不同的蠕虫。

    【讨论】:

      【解决方案4】:

      一堆getc() C 中的演示:

      1。要打印出输入的密钥,请执行以下操作:

      read_in_any_key.c:

      #include <stdio.h>
      
      int main()
      {
          printf("Press any key followed by Enter, or just Enter alone, to continue: ");
          int c = getc(stdin);
          printf("The first character you entered is decimal %i (\"%c\").\n", c, c);
      
          return 0;
      }
      

      示例运行和输出。请注意,在最后一个示例中,我单独按了 Enter,因此它会将其打印为换行符。每个键的十进制数字可以在 ASCII 表中找到,例如:https://en.wikipedia.org/wiki/ASCII#Control_code_chart

      eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_in_enter_key.c -o bin/a && bin/a
      Press any key followed by Enter, or just Enter alone, to continue: abc
      The first character you entered is decimal 97 ("a").
      
      eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_in_enter_key.c -o bin/a && bin/a
      Press any key followed by Enter, or just Enter alone, to continue: def
      The first character you entered is decimal 100 ("d").
      
      eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_in_enter_key.c -o bin/a && bin/a
      Press any key followed by Enter, or just Enter alone, to continue: FTL
      The first character you entered is decimal 70 ("F").
      
      eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_in_enter_key.c -o bin/a && bin/a
      Press any key followed by Enter, or just Enter alone, to continue: 
      The first character you entered is decimal 10 ("
      ").
      

      2。要打印所有键入的键,以防在按下 Enter 之前按下了多个键,请执行以下操作:

      read_in_any_key.c:

      #include <stdint.h>  // For `uint8_t`, `int8_t`, etc.
      #include <stdio.h>   // For `printf()`
      
      // int main(int argc, char *argv[])  // alternative prototype
      int main()
      {
          printf("Press any key followed by Enter, or just Enter alone, to continue: ");
          int c = getc(stdin);
          printf("The first character you entered is decimal %i (\"%c\").\n", c, c);
      
          // If you entered one or more characters above before pressing Enter, they
          // are still in the stdin input stream's buffer, so let's read those out
          // too, up to the newline char (`'\n'`) created by pressing Enter.
          uint32_t charNum = 2;
          while (c != '\n')
          {
              c = getc(stdin);
              if (c == EOF)
              {
                  printf("Failed to get char!\n");
                  break;
              }
              printf("char %-2u = decimal %i (\"%c\").\n", charNum, c, c);
              charNum++;
          }
      
          return 0;
      }
      

      示例运行和输出。我输入abcdefghijklmnop,然后按Enter

      eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_in_any_key.c -o bin/a && bin/a
      Press any key followed by Enter, or just Enter alone, to continue: abcdefghijklmnop
      The first character you entered is decimal 97 ("a").
      char 2  = decimal 98 ("b").
      char 3  = decimal 99 ("c").
      char 4  = decimal 100 ("d").
      char 5  = decimal 101 ("e").
      char 6  = decimal 102 ("f").
      char 7  = decimal 103 ("g").
      char 8  = decimal 104 ("h").
      char 9  = decimal 105 ("i").
      char 10 = decimal 106 ("j").
      char 11 = decimal 107 ("k").
      char 12 = decimal 108 ("l").
      char 13 = decimal 109 ("m").
      char 14 = decimal 110 ("n").
      char 15 = decimal 111 ("o").
      char 16 = decimal 112 ("p").
      char 17 = decimal 10 ("
      ").
      

      3。要仅在单独按下 Enter 时继续,之前没有其他内容,请执行以下操作:

      read_until_only_enter_key.c:

      #include <stdbool.h> // For `true` (`1`) and `false` (`0`) macros in C
      #include <stdio.h>   // For `printf()`
      
      // Clear the stdin input stream by reading and discarding all incoming chars up to and including
      // the Enter key's newline ('\n') char. Once we hit the newline char, stop calling `getc()`, as
      // calls to `getc()` beyond that will block again, waiting for more user input.
      void clearStdin()
      {
          // keep reading 1 more char as long as the end of the stream, indicated by the newline char,
          // has NOT been reached
          while (true)
          {
              int c = getc(stdin);
              if (c == EOF || c == '\n')
              {
                  break;
              }
          }
      }
      
      // Returns true if only Enter was pressed, and false otherwise
      bool getOnlyEnterKeypress()
      {
          bool onlyEnterPressed = false;
          printf("Press ONLY the Enter key to continue: ");
          int firstChar = getc(stdin);
          if (firstChar == '\n')
          {
              printf("Good! You pressed ONLY the Enter key!\n");
              onlyEnterPressed = true;
          }
          else
          {
              printf("You failed. You pressed another key first.\n");
              clearStdin();
          }
          return onlyEnterPressed;
      }
      
      // int main(int argc, char *argv[])  // alternative prototype
      int main()
      {
          while (!getOnlyEnterKeypress()) {};
      
          return 0;
      }
      

      示例运行和输出。请注意,当我只按下 Enter 时,程序直到最后才退出,之前没有更多的键。

      eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_until_only_enter_key.c -o bin/a && bin/a
      Press ONLY the Enter key to continue: a
      You failed. You pressed another key first.
      Press ONLY the Enter key to continue: abc
      You failed. You pressed another key first.
      Press ONLY the Enter key to continue: w
      You failed. You pressed another key first.
      Press ONLY the Enter key to continue:
      Good! You pressed ONLY the Enter key!
      

      如果您想立即阅读按键,而不是等待按下 Enter 键,请参阅下方“进一步了解”部分顶部的链接。

      参考资料:

      1. Answer by @Justiniscoding
      2. https://en.cppreference.com/w/c/io/fgetc
      3. https://www.cplusplus.com/reference/cstdio/getc/

      相关/更进一步:

      1. [我的回答] 如何读取按键 立即 而不是等待输入:Capture characters from standard input without waiting for enter to be pressed
      2. What is the equivalent to getch() & getche() in Linux?
      3. How to avoid pressing Enter with getchar() for reading a single character only?
      4. Read Key pressings in C ex. Enter key

      【讨论】:

        猜你喜欢
        • 2013-04-06
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-21
        • 1970-01-01
        • 2018-12-30
        • 2017-06-26
        • 1970-01-01
        相关资源
        最近更新 更多