Attempt to read keyboard input without locking (Windows, C ++)

I am trying to write a Windows console application (in C ++ compiled with g ++) that will execute a series of instructions in a loop until it is finished OR until ctrl-z is pressed (or some other key press) . The code that I am currently using to catch it does not work (otherwise I would not ask, right?):

if(kbhit() && getc(stdin) == 26) //The code to execute when ctrl-z is pressed 

If I press the key, it will echo, and the application waits until I press Enter to continue. With a value of 26, it does not execute the assigned code. If I use something like 65 to catch a value, it will be redirected to execution if I press A and Enter after that.

Is there a way to passively check an input by throwing it away if it is not what I am looking for or will react correctly when it is what I am looking for? .. and not pressing Enter after?

+4
source share
2 answers

Try ReadConsoleInput to avoid cooked mode, and GetNumberOfConsoleInputEvents to avoid blocking.

+3
source

If g ++ supports conio.h, then you can do something like this:

 #include <conio.h> #include <stdio.h> void main() { for (;;) { if (kbhit()) { char c = getch(); if (c == 0) { c = getch(); // get extended code } else { if (c == 'a') // handle normal codes break; } } } } 

This link may explain you a little more.

+2
source

Source: https://habr.com/ru/post/1307163/


All Articles