【问题标题】:Linux equivalent for conio.h getch()conio.h getch() 的 Linux 等效项
【发布时间】:2015-12-26 19:43:25
【问题描述】:

以前我在支持 #include <conio.h> 头文件的 Windows 上使用 c++/c 编译器,但在我拥有的 Linux 上使用

gcc (Debian 4.9.2-10) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software...

我想要一个与getch() 完全相同的函数。不知道为什么我的编译器不支持头文件#include <conio.h>

在网上搜索后,我得到了this,它说cin.get(); 可能是最接近的等价物,但这两者的不同之处在于,如果我们写getch(),它不会显示在控制台上输入的字符,而如果我们使用cin.get() 输入一个字符,它会在控制台上显示该字符。我不希望角色显示在控制台上。

使用getchar() 也会在控制台上显示字符。

【问题讨论】:

  • 当您学习古老的、特定于平台的 API 而不是标准 C++ 时,就会发生这种情况。
  • coniocurses 都不是标准 C 库。第一个用于 windows,另一个用于 linux(尽管可能存在反之亦然的实现)。
  • 请选择C和C++之一。
  • @WeatherVane curses 是一个工业标准库(SUS 的一部分)而不是“用于 Linux”,它是一个可在无数操作系统上运行的高度可移植的软件。

标签: c++ linux getch


【解决方案1】:

有许多不同的方法可以更便携地执行此操作。最简单的就是使用curses

#include "curses.h"

int main() {
    initscr();
    addstr("hit a key:");
    getch();
    return endwin();
}

【讨论】:

  • 你能解释一下initscr();吗?
  • @Lovely:它初始化 curses 库,在调用任何其他函数之前需要它。 endwin() 然后关闭东西,需要在程序退出之前调用。
【解决方案2】:

有一个线程用以下代码回答了这个问题:

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

char getch() {
    char buf = 0;
    struct termios old = { 0 };
    fflush(stdout);
    if (tcgetattr(0, &old) < 0) perror("tcsetattr()");
    old.c_lflag    &= ~ICANON;   // local modes = Non Canonical mode
    old.c_lflag    &= ~ECHO;     // local modes = Disable echo. 
    old.c_cc[VMIN]  = 1;         // control chars (MIN value) = 1
    old.c_cc[VTIME] = 0;         // control chars (TIME value) = 0 (No time)
    if (tcsetattr(0, TCSANOW, &old) < 0) perror("tcsetattr ICANON");
    if (read(0, &buf, 1) < 0) perror("read()");
    old.c_lflag    |= ICANON;    // local modes = Canonical mode
    old.c_lflag    |= ECHO;      // local modes = Enable echo. 
    if (tcsetattr(0, TCSADRAIN, &old) < 0) perror ("tcsetattr ~ICANON");
    return buf;
 }

它使用 termios 驱动程序接口库,它是 POSIX (IEEE 1003.1) 的一部分

有关此库的更多参考资料,请阅读:The header contains the definitions used by the terminal I/O interfaces

希望对你有帮助。

【讨论】:

  • 我遇到了这个warning: implicit declaration of function ‘read’; did you mean ‘fread’? [-Wimplicit-function-declaration] 15 | if (read(0, &amp;buf, 1) &lt; 0) perror("read()"); | ^~~~ | fread
  • read 是一个系统调用,当你#include &lt;unistd.h&gt; 时提供了原型。虽然我会推荐一种不需要为添加的每个字符更改键盘模式的方法。最好将键盘置于“原始”(非规范)模式一次,获取原始模式所需的所有输入,然后返回“熟”(规范)模式。
猜你喜欢
  • 2023-03-03
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 2020-11-22
  • 2018-11-26
  • 2012-11-08
  • 1970-01-01
相关资源
最近更新 更多