How to cut off input when using getch??? If user repeatedly presses key it screws the game?

I am asking for input for a char by using the _getch() function. The thing is that when a key is pressed multiple times it screws the program because it executes every single key that is entered.

To better explain how this is a problem, I will explain the kind of program I am making. I am asking for the user to enter a letter that will determine an action to be used in battle, like attack, magic, "use item", etc.

1
2
3
4
5
6
7
8
9
10
11
12
char option;

cout<<"Enter your choice for battle: ";

option=getch();

if(option=='a')
//Executes an attack
else if(option=='b')
//Opens magic menu
else if(option=='c')
//Opens item menu 


Suppose the user enters a character, then the program executes an action by the enemy monster. This is where the problem arises, if the user entered multiple keys or if he enters input during the time the monster attacks, the next time it is the user's turn it will execute the first attack automatically because it keeps reading the input.

I want to know how to cut it off, so that it doesn't ruin the program like that, much thanks for any help.
The way to accomplish what you want to do is to stop using the console in ways in which it was specifically designed not to support and to instead start using a GUI framework like SDL or SFML. I recommend SFML, as it is simple, easy, and has lots of tutorials.
Last edited on
closed account (Dy7SLyTq)
while((option = getch()) != '\n') is the best i would come up with. you arent using _getch(). that is a function for windows to get unbuffered input. getch grabs the next character in the buffer. i would personally use <sstream> and <string> however
@DTSCode: Your solution does not solve the problem ;)
You can't*, you just have to be quick about skipping bad data. If the user is holding the key down, though, he kind of deserves what he gets, because key-repeat doesn't kick-in right away.

To eliminate all key input, just get keys until there is nothing ready:

1
2
3
4
5
void flush_input()
  {
  while (kbhit())
    getch();
  }

Once this function terminates, you know that there is no keyboard input waiting to be read. Your user will have to supply a new keypress to continue.

Of course, if he is still holding down a key, he gets what he deserves.

Hope this helps.


* Technically, you can, but this requires a shocking amount of work, a reboot (probably), it is a system-wide change, and it won't work on anything older than Windows 2000.
closed account (Dy7SLyTq)
can't you just use unbuffered input and execute whenever a key is hit?
The getch() function does just that. It does not affect the keyrepeat.
Thanks very much
Topic archived. No new replies allowed.