getch()是编程中所用的函数,这个函数是一个不回显函数,当用户按下某个字符时,函数自动读取,无需按回车,有的C语言命令行程序会用到此函数做游戏,但是这个函数并非标准函数,要注意移植性!
#include <termio.h>
int getch(void)
{
struct termios tm, tm_old;
int fd = 0, ch;
if (tcgetattr(fd, &tm) < 0) {//保存现在的终端设置
return -1;
}
tm_old = tm;
cfmakeraw(&tm);//更改终端设置为原始模式,该模式下所有的输入数据以字节为单位被处理
if (tcsetattr(fd, TCSANOW, &tm) < 0) {//设置上更改之后的设置
return -1;
}
ch = getchar();
if (tcsetattr(fd, TCSANOW, &tm_old) < 0) {//更改设置为最初的样子
return -1;
}
return ch;
}
总体的思路就是设置终端的属性
设置为原始模式,这种模式下输入就是无缓冲的,
设置过去,输入完之后然后再更改回来
主要就是两个函数
tcgetattr()和tcsetattr()
由于在linux中没有conio.h文件,所以不能直接用getch()函数,下面介绍如何在linux中使用getch()函数:
在linux中并没有 conio.h 这个文件,要实现类似 getch()/getche() 等函数的功能,可以使用 curses库。
#include <curses.h>
使用 curses 之前要先进行初始化,用完了要注消————这些操作分别调用 initscr() endwin() 来完成.
main(){
initscr();
.
.
.
endwin();
}
注:在编译的时候如果编译不过,可以试着添加 -l curses 参数来引入 curses 库
例如:
1.建立test.c 文件
#include <stdio.h>
#include "stdlib.h"
#include "string.h"
#include <curses.h>
int main()
{
initscr();
char ch;
int i;
while(1){
ch=getch();
printf("%c",ch);
fflush(stdout);
}
endwin();
return 0;
}
2.用以下命令编译:gcc -o test -l curses test.c
3.运行:./test 即可看到效果