How do I clean input buffer before using getch()? - c++

So, I am using GetAsyncKeyState() to see when some key is pressed. But, after using it I need to use getch(). But it seems that getch() gets whatever GetAsyncKeyState() got before again. That is the version of my simplified code:
#include <graphics.h>
int main()
{
initwindow(100, 100);
while(true)
{
if (GetAsyncKeyState(VK_RETURN)) //wait for user to press "Enter"
break;
//do other stuff
}
getch(); //this is just skipped
return 0;
}
I think I need to clean the input buffer before using getch(). But how?
PS: GetAsyncKeyState() is a must-use for me and I have not found any substitute for getch(), which could work with BGI window and which would fix the problem.
Hoping for some advice and thank you.

Use FlushConsoleInputBuffer
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));

It is skipping getch() call beacuse of enter pressed by user for the previous input, and getch is getting that char, the function fflush(stdin) we flush the input stream.
so that getch() will read the fresh input from input stream.
#include <graphics.h>
int main()
{
initwindow(100, 100);
while(true)
{
if (GetAsyncKeyState(VK_RETURN)) //wait for user to press "Enter"
break;
//do other stuff
}
fflush(stdin);
getch(); //this is just skipped
return 0;
}

Related

How i can get what key was pressed in codeblocks?

How to display what key was pressed?
I mean, like if you press A, on screen will display: You pressed A.
cin>>keypress;
cout<<"You pressed:"<<keypress;
I want to show directly what key I am pressing. Without waiting to press enter and finishing the execution.
I have a Windows only solution using the windows api.
#include <wInDoWs.h>.
you can use GetAsyncKeyState() and pass the ASCII value for the key to it. It will return a short indicating the status of the button. To the best of my knowledge, the value -32767 is returned when the button is pressed. Wrap that in a function and you can tell if the button is pressed. (below will run with copy/paste.)
#include <windows.h>
#include <iostream>
bool pressed(const short& _key)
{
short state = 0;
short pressed= -32767;
state = GetAsyncKeyState( _key);
return ( state == pressed );
}
int main()
{
//see if J is pressed
while(1)
{
if(pressed( 0x4a ) )// 'J'
std::cout << "J";
}
}
To make that work with all characters, I'm afraid I can't think of an easier way than storing all the ASCII values, and what you want to print out if the key is pressed, in a container and checking their pressed status every frame.(below is just pseudo code.)
//the container this short is the 'key'
std::vector< std::pair< short , std::string > > chars;
//to check the status
for(auto& c : chars)
if( pressed( c.first ) ) std::cout << c.second;
I would put that in some sort of loop.
Adding the 'you pressed space' wouldn't be difficult this way.
just do
chars.push_back( std::pair<int,std::string>(0x20 , "Spacebar") );
I think you want to display the character what are you pressing (like in your example). So, it's pretty simple. Here's the code:
#include <stdio.h>
#include <conio.h>
int main()
{
char keyPress;
while(1)
{
keyPress=_getch();
if((keyPress==27)||(keyPress==32))
{
printf("You decided to stop the execution of this code.");
return 0;
}
printf("You pressed:%c\n",keyPress);
}
}
If you let the code how it is, the program will finish the execution on esc or space pressed. If you want to change this, you can replace the numbers in: if((keyPress==27)||(keyPress==32)) with anothers ascii codes of your button. Here's all the ascii codes: https://ascii.cl/ . If you want to end the program only on one button, just modify from if((keyPress==27)||(keyPress==32)) into if(keyPress==27) and now the program will stop only on ESC.

Can't get next user command right after "consoleHandler" function get Ctrl-C from user

I writing a tiny shell for my subject and I need to catch Ctrl-C and handle it. I have a infinity loop to get user command until they type "exit". When I haven't type Ctrl-C everything is ok, my program get user command and handle it one by one. But when I type Ctrl-C, my program don't get any user command from that time. And I have an infinity loop but I can't type anything except for Ctrl-C.
I try to put a fflush(stdin) begore getline but it doesn't work.
I try to list all threads in the process and it is always one. There is always one thread.
#include<iostream>
#include<windows.h>
#include<stdio.h>
#include<stdio.h>
#include<tchar.h>
#include<psapi.h>
#include<vector>
#include<string>
using namespace std;
BOOL WINAPI consoleHandler(DWORD signal)
{
if(signal == CTRL_C_EVENT)
cout << "^C";
return TRUE;
}
int main()
{
SetConsoleCtrlHandler(consoleHandler, TRUE);
string userInput;
while(true)
getline(cin, userInput);
return 0;
}
Expect: After I type CTRL-C console print "^C" and the program will get my next command
Your input stream has an error bit set after Ctrl-C was sent. You need to clear it, otherwise std::getline will not read any characters from the stream and simply return:
BOOL WINAPI consoleHandler(DWORD signal)
{
if (signal == CTRL_C_EVENT)
{
std::cout << "^C\n";
std::cin.clear();
}
return TRUE;
}

Getting input from console without cin?

I'm trying to make a little console program that will basically be console pong. So right now I have this:
int main()
{
while(1)
{
clearScreen();
restThread(100);
}
return 0;
}
The only input I need to poll is if the user has pressed the A or D key since the screen was cleared. I will also need to know when the key is released. I'm also trying to do this cross platform.
so really all I need is like an if(keyWasDown('a')) {} sort of function.
Thanks
Maybe you want kbhit (non-blocking) or getch (blocking), both from <conio.h>. There's also getchar, from <stdio.h> or <cstdio>.
If you want the program to wait for a keyboard press, getch or getchar by themselves will do.
If you don't want the program to wait for a keyboard press, kbhit combined with either getch or getchar will suffice.
However, as GMan said, these methods are not really cross platform (if you never intend to try this on different platforms, that's moot, really). For console games, you might be interested looking into ncurses.
#include <stdio.h>
#include <conio.h>
int main()
{
while(1)
{
clearScreen();
if(kbhit())
{
int const ch = getch();
switch(ch)
{
case 0x61: printf("A was pressed!\n"); break;
case 0x64: printf("D was pressed!\n"); break;
}
}
restThread(100);
}
return 0;
}

How to get user input from a prompt(terminated by press ENTER) in c++?

Anyone knows this tip?
Try getline:
string s;
getline(cin, s);
Return key is the easy case, as Mehrdad answered, just read something from std::cin.
If you want to terminate on a different key press, for example, exit on any key, you can use a couple non-standard calls in conio.h.
#include <conio.h>
// wait for any key press
while (!kbhit()) { }
// wait for q key press
while (!kbhit() || getch() != q) { }
// wait for any key press on windows
system("pause");

Trying to read keyboard input without blocking (Windows, C++)

I'm trying to write a Windows console application (in C++ compiled using g++) that will execute a series of instructions in a loop until finished OR until ctrl-z (or some other keystroke) is pressed. The code I'm currently using to catch it isn't working (otherwise I wouldn't be asking, right?):
if(kbhit() && getc(stdin) == 26)
//The code to execute when ctrl-z is pressed
If I press a key, it is echoed and the application waits until I press Enter to continue on at all. With the value 26, it doesn't execute the intended code. If I use something like 65 for the value to catch, it will reroute execution if I press A then Enter afterward.
Is there a way to passively check for input, throwing it out if it's not what I'm looking for or properly reacting when it is what I'm looking for? ..and without having to press Enter afterward?
Try ReadConsoleInput to avoid cooked mode, and GetNumberOfConsoleInputEvents to avoid blocking.
If G++ supports conio.h then you could 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 things a little more for you.