C ++:执行while循环,直到按下一个键。退出? [英] C++: execute a while loop until a key is pressed e.g. Esc?

查看:611
本文介绍了C ++:执行while循环,直到按下一个键。退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都有一个代码片段不使用 windows.h 来检查while循环中的按键。基本上这个代码,但不必使用 windows.h 来做。我想在Linux和Windows上使用它。

Does anyone have a snippet of code that doesn't use windows.h to check for a key press within a while loop. Basically this code but without having to use windows.h to do it. I want to use it on Linux and Windows.

#include <windows.h>
#include <iostream>

int main()
{
    bool exit = false;

    while(exit == false)
    {
        if (GetAsyncKeyState(VK_ESCAPE))
        {
            exit = true;
        }
        std::cout<<"press esc to exit! "<<std::endl;
    }

    std::cout<<"exited: "<<std::endl;

    return 0;
}


推荐答案

一个自定义的GetAsyncKeyState函数,它将使用#IFDEF作为窗口和linux来选择适当的GetAsyncKeyState()或等效项。

Your best bet is to create a custom "GetAsyncKeyState" function that will use #IFDEF for windows and linux to choose the appropriate GetAsyncKeyState() or equivalent.

没有其他方法可以实现所需的结果, cin方法有其问题 - 例如应用程序必须在焦点。

No other way exists to achieve the desired result, the cin approach has its problems - such as the application must be in focus.

这篇关于C ++:执行while循环,直到按下一个键。退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆