C ++ Alternative to getch ()?


Do you know any alternative to the getch() function? because it's from the Conio library (which is not standard) and I would like to know if there is any standard alternative for C ++.

I have this code:

      tecla = getch();
 } while (tecla != TECLA_ARRIBA && tecla != TECLA_ABAJO && tecla != ENTER);

I do not want a break, I want to capture data like the example code.

Note: or otherwise, any code that emulates the function?

asked by Malthael 21.02.2017 в 23:30

3 answers


I understand that what you want is to read the direct inputs of the keys, without going through the buffer input std::cin .

In that case, the answer is simple: no There is a standard way, since it depends on the operating system you use.

If you're in the console emulation of Windows, you know what to use: conio.h

If you use a graphical application, you have no choice but to resort to the system of events provided by the operating system, or the library of highest level you use.

The most portable mode would be using the ncurses library. Although it is native to * nix systems, it can be used in Windows terminal emulators. In chapter 11 of NCURSES Programming HOWTO , Interfacing with the keyboard , you have a complete example.

As a last option, if you are in Linux, you can set the keyboard in raw mode, directly accessing the events it generates. You have a complete example in Grab Raw Keyboard Input .

answered by 22.02.2017 / 05:31

You can not do what you want. At least not pulling the C ++ standard.

C ++ understands neither keyboards nor consoles but standard input and standard output. This change of concept, although it may seem trivial has its implications:

  • In the case of the keyboard, that the standard does not know that it is dealing with a keyboard implies that it will not be able to recognize the special keys since they are not stored in the input buffer. The standard entry could be a file perfectly and the up arrow or down arrow keys can not be found (for example) and therefore the standard does not provide No special feature to capture these pulsations.
  • In the case of the console, the standard output does not necessarily have to be a console, it can also be a file or it could even be a printer. It is easy to understand then that it does not make sense to speak of rows and columns but of a serial output. It is for this reason that the standard C ++ library does not have any functionality that allows you to place the cursor in a certain position of the console.

The only option left for you is to pull OS-dependent libraries to perform this task: conio.h (Windows), ncurses (Linux), pdcurses (Windows), etc.

answered by 22.02.2017 в 09:18

You can use cin.get( ); of the library iostream and make available the objects cin, cout .


#include <iostream.h>
int main()
    std::cout << "Hola mundo";    
    return 0;
answered by 22.02.2017 в 00:20