我无法在Linux中找到conio.h的等效头文件。什么等同于Linux中的getch()&getche()?
在Linux中有没有getch()
& getche()
函数的选项?
我想制作一个开关盒的基本菜单,用户只需按一个键就可以给出他的选择&过程应该提前。我不想让用户按他的选择后按ENTER键。
我无法在Linux中找到conio.h的等效头文件。什么等同于Linux中的getch()&getche()?
在Linux中有没有getch()
& getche()
函数的选项?
我想制作一个开关盒的基本菜单,用户只需按一个键就可以给出他的选择&过程应该提前。我不想让用户按他的选择后按ENTER键。
#include <termios.h>
#include <stdio.h>
static struct termios old, new;
/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
tcgetattr(0, &old); /* grab old terminal i/o settings */
new = old; /* make new settings same as old settings */
new.c_lflag &= ~ICANON; /* disable buffered i/o */
new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
tcsetattr(0, TCSANOW, &new); /* 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;
}
只需复制这些功能并使用它。我很久以前就在谷歌上找到了这个代码片段,并且我保存了它,最后我在很长一段时间后为你打开了它!希望它有帮助!由于
让我试试,如果它的工作,那么我会接受你的答案...!提前预告.. !! –
嘿谢谢你...你帮了我很多...... !!! –
很高兴听到这个消息,更多的帮助,只需打我们@stackoverflow,我们会帮助你!谢谢! – niko
ncurses库中有一个getch()函数。 你可以通过安装ncurses-dev包来获得它。
在一种情况下,我不想安装新的东西,..任何其他选项? –
您需要编写自己的函数 - 如niko所示。 –
我建议你使用curses.h或ncurses.h这些实现键盘管理例程,包括getch()。您有几个选项来改变getch的行为(即等待按键或不按键)。
char getch(){
/*#include <unistd.h> //_getch*/
/*#include <termios.h> //_getch*/
char buf=0;
struct termios old={0};
fflush(stdout);
if(tcgetattr(0, &old)<0)
perror("tcsetattr()");
old.c_lflag&=~ICANON;
old.c_lflag&=~ECHO;
old.c_cc[VMIN]=1;
old.c_cc[VTIME]=0;
if(tcsetattr(0, TCSANOW, &old)<0)
perror("tcsetattr ICANON");
if(read(0,&buf,1)<0)
perror("read()");
old.c_lflag|=ICANON;
old.c_lflag|=ECHO;
if(tcsetattr(0, TCSADRAIN, &old)<0)
perror ("tcsetattr ~ICANON");
printf("%c\n",buf);
return buf;
}
复制此功能,并使用它,不要忘了包括
remove the last printf if you dont want the char to be displayed
哦很好的解决方法...!将在星期一看我什么时候会在工作..! –
@ mr-32这是与windows的visual studio使用的getch()完全等价的,如果这完全适合您的需要,请减去此函数的最后一行的printf() –
@ mr-32,请标记为正确答案 –
为getch()
更换为stdio.h
声明getchar()
。在Windows和Linux上可以使用getchar()
。
'getch()'和'getchar()'之间有一些(稍微重要的)区别。 1)只要按下键,'getch()'立即返回。 'getchar()'让你无限期地输入,直到你输入一个EOL。 2)'getch()'不会在屏幕上打印任何东西。 'getchar()'将你输入的所有内容写入屏幕(甚至是EOL)。如果这两个差异对用户不重要,那么可以真正使用'getchar()'作为替换,否则这可能不是最好的想法。 –
如上所述,getch()
位于ncurses
库中。 ncurses的,必须初始化,请即getchar() returns the same value (27) for up and down arrow keys此
看看这些答案。可以帮助你:http://stackoverflow.com/questions/1513734/problem-with-kbhitand-getch-for-linux –