I have a problem with do while loop which is escaped when user hit some key. I increase some value by 1 every time it loops. But when I'm printing this value (after every key press) the value is getting printed two times.
The code is as below:
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
int main () {
int x = 0;
char asd;
do {
x++;
asd = getch();
cout << x << " ";
} while(asd!=27);
system("pause");
return 0;
}
I need to check if the key has been pressed, but I dont know how to fix this issue with double printing every time key has been pressed.
Some help?
This is because getch()
reads not only the character you do input, but also the new line feed.
You do actually write some_character
and \n
into the input stream. Both are characters and both are read.
You need to ignore rest of the stream, after the 1st character read.
Another thing it might be is that some keys generate two character codes "0 or 0xE0, and the second call returns the actual key code".
You can see what is really happening with something like this:
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
int main () {
int x = 0;
char asd;
do {
x++;
asd = getch();
cout << "Character code read: " << int(asd)
<< ", character count:" << x << "\n";
} while(asd!=27);
}
This will print actual key codes of what is read, so you will see what is going on.