getchar()、getche()、getch() 函数,它们都用来从控制台获取字符,getchar() 会等待用户按下回车键才开始读取,而 getche()、getch() 会立即读取。这是因为 getchar() 带有缓冲区,用户输入的数据会暂时保存到缓冲区,直到按下回车键才开始读取;而 getche()、getch() 不带缓冲区,只能立即读取。

在windows下,getche()、getch() 都在conio.h头文件定义好了,可以直接拿来用。

但是在linux下没有conio.h这个头文件,通过man getch可知道getch()是存在的,但是getche()不存在

这里写图片描述

使用 getch 等函数,必须使用 curses 库,在 gcc 编译是用 -l curses 加进这个库。
要调用 getch ,程序初始化时应当调用 initscr,否则将出现误。程序结束时,要调用 endwind。

//代码
#include<stdio.h>
#include<stdlib.h>
#include<curses.h>
#include<unistd.h>
int  main(void)
{
    initscr();
    getch();
    sleep(1);
    printf("123456");
    getchar();
    endwin();
    return 0;
}
运行
[limeng@localhost ~]$ vim b.c 
[limeng@localhost ~]$ gcc b.c -lncurses
[limeng@localhost ~]$ ./a.out 
输入1
结果
1123456(光标在此等待,按任意键回到原来的界面)
//这里的结果说明curses.h的getch(),是有回显的

按照我的理解,当调用initscr()时,相当于打开了一个新的虚拟窗口,我输入一个字符,回显出来,停顿一秒后打印出字符串”123456”,然后等待输入,按任意键后,关闭了刚开的虚拟界面(此时程序已经结束),回到了原先的界面,等待执行其他命令。

由此可见,getch在不同系统中的功能是不同的,实现方式也不同,在windows下没有回显,而在linux下却有回显。

那么,怎么在linux实现和windows下getch()和getche()的功能呢?
我们可以写一个conio.h和conio.c文件

//conio.c
#include "conio.h"
#include<stdio.h>

char getch()
{
char c;
system("stty -echo");  //不回显
system("stty -icanon");//设置一次性读完操作,如使用getchar()读操作,不需要按enter
c=getchar();
system("stty icanon");//取消上面的设置
system("stty echo");//回显
return c;
}

char getche()
{
char c;
system("stty -icanon");
c=getchar();
system("stty icanon");
return c; 
}
//conio.h
#ifndef _CONIO_H
#define _CONIO_H

#include <stdio.h>
#include <stdlib.h>

char getch();

char getche();

#endif

在需要用到”conio.h”的文件中只需要包含进去就可以啦!!!

是不是很激动啊!!!

Logo

更多推荐