getch 替代方案

发布于 2024-09-28 01:23:12 字数 185 浏览 5 评论 0原文

正如大多数人所知,getch 会等待用户按下某个键,然后返回值。有没有办法只检查用户当前是否按下某个键?这就是我想做的:

while(1){
char x = getch();
if (x){
//blah
}
else if(y == true){
//blah
}
}

有什么建议吗?

As most know getch waits until the user hits a key and then returns the value. Is there a way in order to just check if the user is currently hitting a key? Here is what I'm trying to do:

while(1){
char x = getch();
if (x){
//blah
}
else if(y == true){
//blah
}
}

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丘比特射中我 2024-10-05 01:23:12

kbhit() 函数(如果您使用的是 Microsoft 的库,则为 _kbhit())。

MSDN: http://msdn.microsoft.com/en- us/library/58w7c94c(VS.80).aspx

“如果按下某个键,_kbhit 将返回一个非零值。否则,它返回 0。”

编辑:正如一些评论者指出的那样,这不是标准的。

There's the kbhit() function (or _kbhit() if you're using Microsoft's libraries).

MSDN: http://msdn.microsoft.com/en-us/library/58w7c94c(VS.80).aspx

"_kbhit returns a nonzero value if a key has been pressed. Otherwise, it returns 0."

EDIT: As some commenters pointed out, it's not standard.

自在安然 2024-10-05 01:23:12

如果您只是想暂停脚本直到按下某个键,那么 getch 就可以工作,但如果您希望他们按下的字符不出现在屏幕上(或者您不关心他们按下的键),您可以使用

system("pause > NUL");

它调用Windows“暂停”命令并将显示的文本和输入(通常显示“按任意键继续...”)路由到一个空的深渊。

另一种方法是使用 GetAsyncKeyState() 等函数并循环遍历所有输入代码以查看当前是否按下了任何键。如果您尝试运行处理循环并希望在用户按下特定键(例如 Escape)时中断,则此方法效果更好。使用它来查看用户是否按下了任何键会浪费大量的处理能力。

If you're just looking to pause the script until a key is pressed, then getch works, but if you want the character they pressed NOT to appear on screen (or you don't care about which key they pressed) you can use

system("pause > NUL");

It calls the Windows "pause" command and routes the displayed text and input (normally it says "Press any key to continue...") into an empty abyss.

The alternative is use a function like GetAsyncKeyState() and looping through all the input codes to see if any key is currently being pressed. This method works much better if you're trying to run a processing loop and want to break out when a user presses a specific key (for example, Escape). Using it to see if the user is pressing any key at all would involve wasting a good bit of processing power.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文