'cin' alternatives

Hello. My question involves cin as a way to gather user input. When I run the program below and press backspace to inter input, the keystrokes previously pressed will automatically be entered into the input space.

For example, if I press ggghhh while I’m moving around with the arrows and press backspace, ggghhh will pop into the input field before I type anything. (Which also happens with the direction keys or q - for quit - if I were to use GetAsyncKeyState instead of GetKeyState.)

I’ve tried clearing the buffer right before I ask for input, but that hasn’t helped. Is there a method to collect user input without having the previously pressed keys clog the field?

Below is the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "Player.h"
#include <iostream>
#include<iomanip>
#include <string>
#include <windows.h>
using namespace std;


int main(void)
{

	Player player;
	player.x_pos = 0;
	player.y_pos = 0;
	char player_input[100];
	

cout << "Welcome to the game. To move, just use the arrow keys. To enter commands, press backspace. If you need help, enter help." << endl;

		for(;;)
		{
	
		
			//Movement by pressing the arrow keys
			if(GetKeyState(VK_LEFT)<0)
			{
				player.move("left");
			}
			if(GetKeyState(VK_RIGHT)<0)
			{
				player.move("right");
			}
			if(GetKeyState(VK_UP)<0)
			{
				player.move("up");
			}
			if(GetKeyState(VK_DOWN)<0)
			{
				player.move("down");
			}
			
				
				
			//Enter command by pressing ‘Backspace’
			if(GetKeyState(VK_BACK)<0)
			{
				cout << "This is before." << endl;
				
				std::cin.getline(player_input, 100, '*');
				
				cout << "And this is after." << endl;
				
				cout << player_input << endl;
			}
			


			//Quit by pressing ‘Q’
			if(GetKeyState(0x51)<0)
			{
				break;
			}

			Sleep(10);

			
		}
		

}
Topic archived. No new replies allowed.