我找不到conio的等效头文件.Linux中的h.

Linux中是否有getch()&getche()功能的选项?

我想做一个基于 case 的切换菜单,用户只需按下一个键就可以给出他的 Select ,而且过程应该向前移动.我不想让用户在按下他的 Select 后再按回车键.

推荐答案

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

static struct termios old, current;

/* Initialize new terminal i/o settings */
void initTermios(int echo) 
{
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  current = old; /* make new settings same as old settings */
  current.c_lflag &= ~ICANON; /* disable buffered i/o */
  if (echo) {
      current.c_lflag |= ECHO; /* set echo mode */
  } else {
      current.c_lflag &= ~ECHO; /* set no echo mode */
  }
  tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void) 
{
  tcsetattr(0, TCSANOW, &old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo) 
{
  char ch;
  initTermios(echo);
  ch = getchar();
  resetTermios();
  return ch;
}

/* Read 1 character without echo */
char getch(void) 
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void) 
{
  return getch_(1);
}

/* Let's test it out */
int main(void) {
  char c;
  printf("(getche example) please type a letter: ");
  c = getche();
  printf("\nYou typed: %c\n", c);
  printf("(getch example) please type a letter...");
  c = getch();
  printf("\nYou typed: %c\n", c);
  return 0;
}

输出:

(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g

C++相关问答推荐

EXTI中断在STM 32 H7上触发两次

如何在不修改字符串缓冲区早期使用的情况下覆盖字符串缓冲区

exit(EXIT_FAILURE):Tcl C API类似功能

ESP32在vTaskDelay上崩溃

如何在C客户端应用程序的ClientHello消息中添加自定义扩展?

Linux不想运行编译后的文件

如何使用指向 struct 数组的指针并访问数组中特定索引处的 struct

在Rust和C之间使用ffi时如何通过 struct 中的[U8;1]成员传递指针

在Linux上使用vscode和lldb调试用Makefile编译的c代码

编译器如何处理具有更复杂值的枚举?

指向不同类型的指针是否与公共初始序列规则匹配?

Fprintf正在写入多个 struct 成员,并且数据过剩

使用正则表达式获取字符串中标记的开始和结束

如何修复我的qsort()算法?它每次都给出不同的结果

为什么GCC 13没有显示正确的二进制表示法?

即使客户端不发送数据,也会发生UNIX套接字读取

从系统派生线程调用CRT

gdb - 你能找到持有内部 glibc 锁的线程吗?

无法将字符串文字分配给 C 中的字符数组

如何为avr atmega32微控制器构建C代码,通过光电二极管捕获光强度并通过串行通信传输数据