我有一个程序如下:
#include<iostream>
using namespace std;
int main()
{
while(true)
{
//do some task
if(Any_key_pressed)
break;
}
return 0;
}
如果按任何键,如何退出循环。
C++ Compiler: GCC 4.2 and higher
OS: Linux-Mint
由于
答案 0 :(得分:3)
标准C ++没有提供这样做的方法。您将需要一个特定于平台的API,告诉您是否按下了键(或者可能在stdin上输入了键)而没有阻塞。这意味着您需要告诉我们您正在使用哪个平台。
答案 1 :(得分:1)
试试这个:
#include <iostream>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
using namespace std;
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
int main(void)
{
while(!kbhit());
cout<<"You pressed "<<(char)getchar();
return 0;
}
答案 2 :(得分:1)
您可以使用SDL,它(主要)与平台无关。
#include<SDL/SDL.h>
...
#include<iostream>
using namespace std;
int main()
{
while(true)
{
//do some task
SDL_Event event
while(SDL_PollEvent(&event))
{
if(event.type==SDL_KEYDOWN)
{
break;
}
}
}
return 0;
}
以上代码适用于Windows,Linux,MacOS以及其他多种操作系统。 至于如何设置SDL,有一个tutorial。
答案 3 :(得分:0)
您可以使用ncurses:
#include <iostream>
#include <ncurses.h>
int main ()
{
initscr(); // initialize ncurses
noecho(); // don't print character pressed to end the loop
curs_set(0); // don't display cursor
cbreak(); // don't wait for user to press ENTER after pressing a key
nodelay(stdscr, TRUE); // The nodelay option causes getch to be a non-blocking call. If no input is ready, getch returns ERR. If disabled (bf is FALSE), getch waits until a key is pressed.
int ch;
printw("Let's play a game! Press any key to quit.\n\n");
while (1) { // infinite loop
if ((ch = getch()) == ERR) { // check to see if no key has been pressed
printw("."); // if no key has been pressed do this stuff
usleep(1000);
refresh();
} else { // if a key is pressed...
nodelay(stdscr, false); // reset nodelay()
clear(); // clear the screen
break; // exit loop
}
}
mvprintw(LINES/2, COLS/2-9, "Game Over");
refresh();
getch(); // wait for character, just so the program doesn't finish and exit before we read "Game Over"
endwin(); // terminate ncurses
return 0;
}