Getting input from console without cin? - c++

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;
}

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.

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

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;
}

how to detect arrow keys

I have created an application for detect pressing up and down key on keyboard
but nothing will be printed after pressing these keys.
I am using Visual C++ 2010
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
char x;
while(1)
{
x = getch();
if(x==0 || x==224)
{
x=getch();
if(x==80)
{
cout << "down"<<endl;
}
else if(x==72)
{
cout << "up"<<endl;
}
}//if x==0 || x=224
}//while1
}//main
What can be the problem?
Thanks
Just to answer why it isn't working: You are trying to use your user's input as unsigned. Your character variable is signed so the value is different than you are expecting. An unsigned 224 is a signed -32.
As far as your loop goes I'd suggest changing things to this.
void main()
{
char x;
while(true)
{
while(!kbhit()){}
x = getch();
if(x==0 || x==-32)
{
x=getch();
if(x==80)
{
cout << "down"<<endl;
}
else if(x==72)
{
cout << "up"<<endl;
}
}//if x==0 || x=224
}//while1
}//main
The program will still loop forever. Then the next loop, which I added, will continue to loop while there are no keys being pressed(buffered). Then getch() grabs the next char from the buffer. Now the problem you were running into, is that you had 224 (0xE0) which is technically correct. However in binary apparently -32 and 224 look the same.
I ran into a bit of the same issue at first, I couldn't figure out why my code wasn't hitting the correct code block and it was because the first character was actually -32 (0xE0)
Hope that is of some help, despite this being a really old question.
You can use the curses.h library. Read their guide and it should be very easy from there.
After you take input using getch() (store the input into an int, not a char), you can verify if it's one of the arrow keys using the defined keycodes. Just make sure you used keypad(stdscr, TRUE) before for the program to be able to recognize the arrow keys.
Us kbhit() to get Keyboard Arrow Keys

Getting arrow keys from cin

I am sure this must have been asked before, but a quick search found nothing.
How can I get the arrow/direction keys with cin in c++?
It has indeed been asked before, and the answer is that you cannot do it.
C++ has no concept of a keyboard or a console. It only knows of an opaque input data stream.
Your physical console preprocesses and buffers your keyboard activity and only sends cooked data to the program, usually line-by-line. In order to talk to the keyboard directly, you require a platform-specific terminal handling library.
On Linux, this is usually done with the ncurses or termcap/terminfo libraries. On Windows you can use pdcurses, or perhaps the Windows API (though I'm not familiar with that aspect).
Graphic-application frameworks such as SDL, Allegro, Irrlicht or Ogre3D come with full keyboard and mouse handling, too.
Here is a pointer if you dont mind using getch() located in conio.h.
#include <stdio.h>
#include <conio.h>
#define KB_UP 72
#define KB_DOWN 80
#define KB_LEFT 75
#define KB_RIGHT 77
#define KB_ESCAPE 27
int main()
{
int KB_code=0;
while(KB_code != KB_ESCAPE )
{
if (kbhit())
{
KB_code = getch();
printf("KB_code = %i \n",KB_code);
switch (KB_code)
{
case KB_LEFT:
//Do something
break;
case KB_RIGHT:
//Do something
break;
case KB_UP:
//Do something
break;
case KB_DOWN:
//Do something
break;
}
}
}
return 0;
}

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.