C++:执行一个while 循环,直到按下一个键,例如Esc?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15737495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++: execute a while loop until a key is pressed e.g. Esc?
提问by pandoragami
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.
有没有人有一段代码不windows.h
用于检查 while 循环中的按键。基本上是这段代码,但不必使用windows.h
它。我想在 Linux 和 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;
}
采纳答案by gongzhitaao
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.
最好的办法是创建一个自定义的“GetAsyncKeyState”函数,该函数将使用 #IFDEF for windows 和 linux 来选择适当的 GetAsyncKeyState() 或等效函数。
No other way exists to achieve the desired result, the cin approach has its problems - such as the application must be in focus.
没有其他方法可以达到预期的结果,cin 方法有其问题 - 例如应用程序必须聚焦。
回答by Nasir Mahmood
#include <conio.h>
#include <iostream>
int main()
{
char c;
std::cout<<"press esc to exit! "<<std::endl;
while(true)
{
c=getch();
if (c==27)
break;
}
std::cout<<"exited: "<<std::endl;
return 0;
}
回答by gongzhitaao
char c;
while (cin >> c) {
...
}
ctrl-D
terminates the above loop. It will continue so long as a char is entered.
ctrl-D
终止上述循环。只要输入字符,它就会继续。
回答by AmmAr
//simplest.
//最简单。
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char ch;
bool loop=false;
while(loop==false)
{
cout<<"press escape to end loop"<<endl;
ch=getch();
if(ch==27)
loop=true;
}
cout<<"loop terminated"<<endl;
return 0;
}
回答by Not Larangi
//its not the best but it works
#include <vector>
#define WINVER 0x0500
#include <windows.h>
#include <conio.h>
#include <iostream>
int main()
{
char c;
std::cout<<"press esc to exit! "<<std::endl;
while(true)
{
std::cout<<"executing code! , if code stops press any key to continue or esc to stop"<<std::endl;
INPUT ip;
// Set up a generic keyboard event.aa
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0; // hardware scan code for key
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
int lol = 65; //a key
// Press the "A" key
ip.ki.wVk = lol; // virtual-key code for the "a" key
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));
// Release the "A" key
ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
SendInput(1, &ip, sizeof(INPUT));
c=getch();
if (c==27)
break;
}
std::cout<<"exited: "<<std::endl;
return 0;
}