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;
}
Related
I have been tackling this problem for almost two sleepless(?) weeks now. I'm creating a program that will read from a text file and prints getline() with a period '.' delimiter. I want to read each sentence AND also check for the strings "[INT]" and the like.
This program is a rudimentary text-based visual novel, and thus needs choices, stats and save algorithms.
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
#include <ctype.h>
using namespace std;
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
#define ENTER 13
#define ESC 27
#define BACKSPACE 8
int main()
{
if(!loadfile)
{
cout<<"\n\n[Load a Saved File First.]\n\n\n\n";
system("pause");
//loadgame(); unimportant for now
}
menu = true;
system("cls");
ifstream novel("Novels\\main.vnt");
fstream backlog;
backlog.open("backlog.txt");
pagex=0;
/*while(pagex!=page)
{
//loop until pagex = page
}*/
string title = "title ", line;
getline(novel, line);
system(("title "+line).c_str());
while(menu)
{
c=0;
switch((c=getch()))
{
case KEY_DOWN:
getline(novel, line, '.');
line += ".";
backlog<<line;
page++;
cout<<line;
break;
case KEY_UP:
while(getline(backlog, logline))
{
cout<<logline;
system("pause");
}
break;
//case 's':
//case 'S':
// savegame(1, 's'); unimportant for now
case ESC:
menu = false;
//goto character; unimportant for now
break;
case ENTER:
/*In this part, the code should loop (using page as a counter)
until it reaches one of the special formats (like "[INT]",
"[PAT]", "[CHOICE]" and so on*/
break;
}
//character:
//character(); unimportant for now
system("pause");
return 0;
}
As for the format of the story:
Hello there.
[CHOICE]:
[INT]: I'm so smart.
[PAT]: I'm so patient.
[CHR]: I'm so charming.
[SAN]: I'm so sane.
[INT](
Yeah, right. I can't even finish this sente
)
[PAT}(
Yeah, right. You do know you should pass this tomorrow, right?
)
[CHR](
Yeah, right. Why does my heart beat fast?
)
[SAN](
Hurr, durr.
)
I've tried reading a line and saving it instead rather than using a number, but due to the sentence-based printing, I can't just up and save a line and expect the user to understand where he left off when he reads
"ere are you?", said the maid. Apparently, standardiza"
Please help.
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
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 make the hardware beep sound with c++?
Print the special character ASCII BEL (code 7)
cout << '\a';
Source
If you're using Windows OS then there is a function called Beep()
#include <iostream>
#include <windows.h> // WinApi header
using namespace std;
int main()
{
Beep(523,500); // 523 hertz (C5) for 500 milliseconds
cin.get(); // wait
return 0;
}
Source: http://www.daniweb.com/forums/thread15252.html
For Linux based OS there is:
echo -e "\007" >/dev/tty10
And if you do not wish to use Beep() in windows you can do:
echo "^G"
Source: http://www.frank-buss.de/beep/index.html
There are a few OS-specific routines for beeping.
On a Unix-like OS, try the (n)curses beep() function. This is likely to be more portable than writing '\a' as others have suggested, although for most terminal emulators that will probably work.
In some *BSDs there is a PC speaker device. Reading the driver source, the SPKRTONE ioctl seems to correspond to the raw hardware interface, but there also seems to be a high-level language built around write()-ing strings to the driver, described in the manpage.
It looks like Linux has a similar driver (see this article for example; there is also some example code on this page if you scroll down a bit.).
In Windows there is a function called Beep().
alternatively in c or c++ after including stdio.h
char d=(char)(7);
printf("%c\n",d);
(char)7 is called the bell character.
You could use conditional compilation:
#ifdef WINDOWS
#include <Windows.h>
void beep() {
Beep(440, 1000);
}
#elif LINUX
#include <stdio.h>
void beep() {
system("echo -e "\007" >/dev/tty10");
}
#else
#include <stdio.h>
void beep() {
cout << "\a" << flush;
}
#endif
std::cout << '\7';
Here's one way:
cout << '\a';
From C++ Character Constants:
Alert: \a
#include<iostream>
#include<conio.h>
#include<windows.h>
using namespace std;
int main()
{
Beep(1568, 200);
Beep(1568, 200);
Beep(1568, 200);
Beep(1245, 1000);
Beep(1397, 200);
Beep(1397, 200);
Beep(1397, 200);
Beep(1175, 1000);
cout<<endl;
_getch()
return 0
}
I tried most things here, none worked on my Ubuntu VM.
Here is a quick hack (credits goes here):
#include <iostream>
int main() {
system("(speaker-test -t sine -f 1000)& pid=$!; sleep 1.0s; kill -9 $pid");
}
It will basically use system's speaker-test to produce the sound. This will not terminate quickly though, so the command runs it in background (the & part), then captures its process id (the pid=$1 part), sleeps for a certain amount that you can change (the sleep 1.0s part) and then it kills that process (the kill -9 $pid part).
sine is the sound produced. You can change it to pink or to a wav file.
Easiest way is probbaly just to print a ^G ascii bell
The ASCII bell character might be what you are looking for. Number 7 in this table.
cout << "\a";
In Xcode, After compiling, you have to run the executable by hand to hear the beep.
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.