【问题标题】:I'm writing a C program and I can't figure out how to insert "Press any key to continue..." and have it continue after any key and not just enter我正在编写一个 C 程序,但我不知道如何插入“按任意键继续...”并让它在任意键之后继续,而不仅仅是输入
【发布时间】:2020-02-18 02:48:14
【问题描述】:

我正在编写一个带有 switch 语句和 while 循环的菜单驱动程序。我的教授希望我们包含“按任意键继续...”并说为此使用 getchar()。他说如果需要我们按回车键,我们会丢分,这就是我使用 getchar() 时发生的情况。

我看过很多关于使用 getch() with 的帖子,但是这不起作用,因为我使用的是用 cygwin 编译和执行的 C 程序。

提前致谢

编辑 更新,因为我没有看到任何使用 Unix/Linux 的特定问题的答案...... 给我的教授发了电子邮件,他给我回复了这个......

“Unix/Linux 问题。键盘输入/输出是缓冲的,即,您的程序可能不会在用户按下某个键后立即获取该字符。通常,操作系统 (OS) 将发送在 ENTER 键后按下的字符被按下。如果您希望您的程序在用户按下它后立即获取字符,请在您的 shell(命令窗口或终端)中运行以下命令。您只需在第一次打开 shell 后运行一次 stty -icanon min 1

我在编译之前在shell中执行了这个命令,它仍然没有工作。

然后我使用 getchar();连续两次,因为之前使用了 scanf 并且不消耗使用的输入并将其传递给第一个 getchar();

现在可以了,我可以按任意键继续...

【问题讨论】:

  • 那么你需要使用getchar()吗?或者任何输入法?
  • 他不要求我们使用getchar(),这只是他建议的方法。
  • 我假设您需要将此作为作业提交。在麻烦寻找解决方法之前,会用 Cygwin 编译它吗?
  • 是的,代码在实验室中演示并由教授查看。是的,它是用 Cygwin 编译的,所以 getch() 在这种情况下不起作用,但 getch() 是我能找到的唯一其他解决方案。
  • 你可以试试scanf, fgetc(stdin) / fgetc(stdin) 或者试试fgets 大小为1或0。

标签: c cygwin getchar getch


【解决方案1】:

对于 Linux,我使用以下代码。

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int getch (void)
{
// Declare variables.
    int c = {0};
    struct termios oldt = {0};
    struct termios newt = {0};

// Get terminal attributes.
    tcgetattr(STDIN_FILENO, &oldt);
// Store attributes.
    newt = oldt;
// Set terminal to non-buffered.
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
// Get user input.
    c = getchar();
// Reset terminal attributes.
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

// Return character.
    return(c);
}

对于 Windoze,只需使用 #include &lt;conio.h&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2013-11-10
    • 2015-01-23
    • 2020-08-10
    • 1970-01-01
    • 2010-11-29
    相关资源
    最近更新 更多