有没有办法在标准 C++ 中直接从键盘读取输入?

2022-01-11 00:00:00 input keyboard console c++

我知道有 std::cin,但这需要用户输入一个字符串,然后按 ENTER.有没有一种方法可以简单地获取按下的下一个键而无需按 ENTER 确认

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

推荐答案

可以使用

#include <conio.h>

然后用这种情况捕获字符

and then catch char with cases such as this

char c;
if (_kbhit())
{
  c = getch();
  switch(c)
  {
  case ‘H’ :
  cout << "up arrow key!" << endl;
  break;
  }
}

注意:我没试过……记得把整个东西放到while(true)"中测试一下.

Beware: I have not tried it... and remember to put the whole thing into a "while(true)" to test.

相关文章