有沒有辦法在標準 C++ 中直接從鍵盤讀取輸入? (Is there a way to read input directly from the keyboard in standard C++?)


問題描述

有沒有辦法在標準 C++ 中直接從鍵盤讀取輸入? (Is there a way to read input directly from the keyboard in standard C++?)

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

‑‑‑‑‑

參考解法

方法 1:

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>.

方法 2:

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.

It supports a wide variety of terminal interfaces.

方法 3:

You can use 

#include <conio.h>

and then catch char with cases such as this

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.

(by user98188Jesse Bederπάντα ῥεῖDervin Thunk)

參考文件

  1. Is there a way to read input directly from the keyboard in standard C++? (CC BY‑SA 3.0/4.0)

#Console #input #C++ #Keyboard






相關問題

grails 日誌消息未顯示在 STS 3.0 控制台上 (grails log messages not displaying on STS 3.0 console)

在 AppFog 上,如何在終端(node.js)上查看控制台日誌 (on AppFog, how to see the console logs on the terminal (node.js))

控制台應用程序中的多個參數未正確解析 (Multiple args in Console Application not parsing correctly)

WPF 應用程序沒有輸出到控制台? (No output to console from a WPF application?)

用 .NET 4.5 編寫的 Windows 服務中的 Console.Out 和 Console.Error 競爭條件錯誤 (Console.Out and Console.Error race condition error in a Windows service written in .NET 4.5)

Visual Basic 2013 - 控制台輸入令牌? (Visual Basic 2013 - Console Input Tokens?)

帶有 stringbuilder 日曆表的控制台日曆 (Console Calendar with stringbuilder calendar sheet)

增加和減少混淆 (Incrementing and Decrementing Confusion)

有沒有辦法在標準 C++ 中直接從鍵盤讀取輸入? (Is there a way to read input directly from the keyboard in standard C++?)

是否可以在方案中編寫控制台應用程序? (Is it possible to write console applications in scheme?)

犀牛的控制台輸入功能? (console input function for rhino?)

輸出中的 PowerShell 空白 (PowerShell gaps in output)







留言討論