当我输入一个字符时,getch 返回 2 个字符
当我使用 getch 时,它总是在读取的字符后面附加一个空字符.
When I use getch, it always appends the caracter read with a null character.
当我使用以下代码时:
#include "stdafx.h"
#include <conio.h>
int main()
{
char c = 0;
while (c != 'x')
{
c = _getch();
printf("Char read: <%c>
", c);
}
}
当我按下asdx"键时,它会在控制台上返回以下内容:
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>
这是在 VS 2017 中编译的一个普通的新单文件项目,在 Windows 10 控制台窗口上运行.我尝试删除 _UNICODE 和 UNICODE 定义.
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.
推荐答案
好吧,废话!
这是 Windows 中的一个(相当新的)错误.
It's a (rather new) bug in windows.
https://developercommunity.visualstudio.com/content/problem/247770/-getch-broken-in-vs-157.html
"使用 _getch() 函数构建控制台应用程序时每次按键突然返回两次"
"When building a console application using the _getch() function suddenly returns two times for each keypress"
从微软得到以下回复:
" 感谢您报告此问题!这将在未来的窗口中修复更新."
" Thanks for reporting this! This will be fixed on a future windows update."
更新:如上面的链接所述,将运行时设置为 静态链接 与 C 运行时的先前版本 将解决问题,但您需要确保所有相关项目(例如,如果您正在构建库)也使用相同的运行时.(我测试过)
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)
相关文章