如何检测用户在C ++(控制台)中是否按任何键? [英] How can I detect if any key is pressed by the user in C++ (console)?
问题描述
我正在编写一个C ++ CLI应用程序,如何检测用户是否按下任何键。我已经看到在c#,但如何在c ++中实现
I am writing a C++ CLI application how can I detect if any key is pressed by the user. I've seen that in c# but how can it be implement in c++
while(1)
{
while(/* code to check if any key is pressed*/)
{ //rest of the code
// sleep function
}
}
提示:像在CLI游戏中移动或采取某些动作,当按下一个键或不做任何事如果没有输入。
Hint: like in CLI games to move or to take certain action when a key is pressed or don't do any thing if no input is given.
推荐答案
我们可以在c ++中使用_kbhit如果按任何键,_kbhit等于1。你必须清除_kbhit缓冲区,否则它将保持为1.清除的方法是character = getch();这将保存最后输入的键的字符,您可以比较,并决定要对哪个键执行哪个操作。
we can use _kbhit() function in c++. _kbhit is equal to 1 if any key is pressed. You have to clear the _kbhit buffer else it will remain 1. Method for clearing is character = getch(); This will save the last entered key in character which you can compare and decide which action to perform on which key.
这篇关于如何检测用户在C ++(控制台)中是否按任何键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!