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.
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 €)Well, crap!
It's a (rather new) bug in windows.
https://developercommunity.visualstudio.com/content/problem/247770/-getch-broken-in-vs-157.html
got the following response from microsoft:
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)