When I use getch, it always appends the caracter read with a null character.
When I use the following code:
#include "stdafx.h"
#include <conio.h>
int main()
{
char c = 0;
while (c != 'x')
{
c = _getch();
printf("Char read: <%c> \n", c);
}
}
It returns the follwing on the console, when I press the keys "asdx":
Char read: <a>
Char read: < >
Char read: <s>
Char read: < >
Char read: <d>
Char read: < >
Char read: <x>
This is compiled in VS 2017 in a plain new single file project, running on a windows 10 console window. I tried removing the _UNICODE and UNICODE define.
Well, crap!
It's a (rather new) bug in windows.
https://developercommunity.visualstudio.com/content/problem/247770/-getch-broken-in-vs-157.html
"When building a console application using the _getch() function
suddenly returns two times for each keypress"
got the following response from microsoft:
" Thanks for reporting this! This will be fixed on a future windows
update."
UPDATE:
As stated in the link above, setting the runtime to statically link with a previous version of the C runtime will fix the issue, but you need to make sure all your related projects (if you are building a library, for example) also use the same runtime. (I tested it)
If you don't want to (or you can't) use a previous version of the Universal C Runtime, you can use _getwch
instead of _getch
, as the problem doesn't affect to _getwch
function.
Note that _getwch
can return Unicode characters, so it may return distinct values than _getch
for some keys. For example, for €
character, _getch
returns 0x3f (?
) while _getwch
returns 0x20ac (Unicode value for €)