0

How do I detect if a key is being held down in C++? An example of how I'd like to use it:

while (varOne == 0) {
    if ('A' Key Pressing Code Detection Magic Goes Here) {
        std::cout << "The 'A' key has been pressed.";
        varOne = 2;
    }
}

I have found a few articles saying to use the conio.h library, however a bunch of people advise against using it. Should I use conio.h? Or is there some other method? (Not sure if it matters, but I'm using VS Code on Linux.)

drescherjm
  • 10,365
  • 5
  • 44
  • 64
Lukas
  • 17
  • 5
  • 2
    ***Should I use conio.h?*** On linux? Related: [https://stackoverflow.com/questions/8792317/where-is-the-conio-h-header-file-on-linux-why-cant-i-find-conio-h](https://stackoverflow.com/questions/8792317/where-is-the-conio-h-header-file-on-linux-why-cant-i-find-conio-h) – drescherjm May 08 '21 at 15:31
  • What 'key' do you use? if it is a simple character you can use getchar(). It looks like you want the 'A' key, so getchar() will do the job. – debanshu das May 08 '21 at 15:41
  • 2
    Standard C++ has no concept of "keyboards", so all questions like this are implementation- and OS-dependent. It definitely matters that you are using Linux, and so you should check the articles you read that they are also meant for Linux. `conio.h` is an ancient header from MS-DOS. – Nate Eldredge May 08 '21 at 16:20

1 Answers1

3

Since your on linux, you might want to look for a curses library. Possible helpful info for ncurses (the modern C++ curses library):

https://www.linuxjournal.com/content/getting-started-ncurses,

https://invisible-island.net/ncurses/,

https://www.cyberciti.biz/faq/linux-install-ncurses-library-headers-on-debian-ubuntu-centos-fedora/.

I'm not a real expert on linux, but this may help.

The accepted answer here : Where is the <conio.h> header file on Linux? Why can't I find <conio.h>? explains a bit on conio.h and ncurses.