This question already has an answer here:
这个问题在这里已有答案:
- Capture characters from standard input without waiting for enter to be pressed 15 answers
从标准输入中捕获字符,无需等待输入按下15个答案
And I know there's std::cin
, but that requires the user to enter a string, then press ENTER. Is there a way to simply get the next key that is pushed without needing to press ENTER to confirm
我知道有std :: cin,但这需要用户输入一个字符串,然后按ENTER键。有没有办法简单地获得推送的下一个键,而无需按ENTER确认
3 个解决方案
#1
You can use
您可以使用
#include <conio.h>
and then catch char with cases such as this
然后用这样的案例捕获char
char c;
if (_kbhit())
{
c = getch();
switch(c)
{
case ‘\0H’ :
cout << "up arrow key!" << endl;
break;
}
}
Beware: I have not tried it... and remember to put the whole thing into a "while(true)" to test.
要注意:我没有尝试过......并且记得把整个事情放到“while(true)”进行测试。
#2
What you're looking for is related to manipulating the console, and is OS-dependent. If you're in a UNIX-based OS, check out the curses library, and in Windows, there are getch()
and kbhit()
functions from <conio.h>
.
您正在寻找的是与操纵控制台有关,并且与操作系统有关。如果您使用的是基于UNIX的操作系统,请查看curses库,在Windows中,可以使用
#3
It looks like the most upvoted answer is a bit outdated.
看起来最受欢迎的答案有点过时了。
The ncurses library (based on the mentioned curses library) is a portable implementation available for unix and linux based operating systems, windows and others.
ncurses库(基于提到的curses库)是一个可移植的实现,可用于基于unix和linux的操作系统,窗口和其他。
It supports a wide variety of terminal interfaces.
它支持各种终端接口。
#1
You can use
您可以使用
#include <conio.h>
and then catch char with cases such as this
然后用这样的案例捕获char
char c;
if (_kbhit())
{
c = getch();
switch(c)
{
case ‘\0H’ :
cout << "up arrow key!" << endl;
break;
}
}
Beware: I have not tried it... and remember to put the whole thing into a "while(true)" to test.
要注意:我没有尝试过......并且记得把整个事情放到“while(true)”进行测试。
#2
What you're looking for is related to manipulating the console, and is OS-dependent. If you're in a UNIX-based OS, check out the curses library, and in Windows, there are getch()
and kbhit()
functions from <conio.h>
.
您正在寻找的是与操纵控制台有关,并且与操作系统有关。如果您使用的是基于UNIX的操作系统,请查看curses库,在Windows中,可以使用
#3
It looks like the most upvoted answer is a bit outdated.
看起来最受欢迎的答案有点过时了。
The ncurses library (based on the mentioned curses library) is a portable implementation available for unix and linux based operating systems, windows and others.
ncurses库(基于提到的curses库)是一个可移植的实现,可用于基于unix和linux的操作系统,窗口和其他。
It supports a wide variety of terminal interfaces.
它支持各种终端接口。