When a special character such as left-arrow is pressed, getch
will first return either the value 0 or 0xE0, then it will return a key code (which is not the same as an ASCII code).
From MSDN:
The _getch
and _getwch
functions read a single character from the
console without echoing the character. None of these functions can be
used to read CTRL+C. When reading a function key or an arrow key, each
function must be called twice; the first call returns 0 or 0xE0, and
the second call returns the actual key code.
So you need to check for a 0 or 0xE0 which tells you the next character is a key code, not an ASCII code.
The list of key codes: https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
EDIT:
Your if(ch1 != 0xE0)
is outside of any case
, so it gets skipped over. Also, you're always calling getch
twice when you enter the loop. So if you didn't get a key code, you end up reading 2 regular characters and most likely skip one of them.
Start you loop with a single getch
. Then check for 0 or 0xE0, and if found then call getch
again.
while (1) {
int ch = getch();
int keycode = 0;
if (ch == 0 || ch == 0xe0) {
keycode = 1;
ch = getch();
}
switch (ch) {
...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…