Reputation: 11
I'm trying to create a binary clock program that runs continually, and only quits when the user presses any key, aka any input.
Looking at other similar questions, detecting specific inputs is easy, but I would have to check for literally every single key for a similar effect.
while(!input)
{
//detect user input to make input=true
//The clock program
}
Upvotes: 0
Views: 2001
Reputation: 1329
Your problem is really platform dependent.
On any Unix platform with curses and or ncurses:
#include <curses.h>
int main(int argc, char **argv)
{
initscr();
cbreak();
// Do something...
printw("press any key to exit...");
getch();
endwin();
return 0;
}
Certainly, you need to link proper library during complation with -lcurses
or -lncurses
.
In Windows it's more complex:
#include <windows.h>
int PressAnyKey( const char *prompt )
{
DWORD mode;
HANDLE hstdin;
INPUT_RECORD inrec;
DWORD count;
char default_prompt[] = "Press a key to continue...";
/* Set the console mode to no-echo, raw input, */
/* and no window or mouse events. */
hstdin = GetStdHandle( STD_INPUT_HANDLE );
if (hstdin == INVALID_HANDLE_VALUE
|| !GetConsoleMode( hstdin, &mode )
|| !SetConsoleMode( hstdin, 0 ))
return 0;
if (!prompt) prompt = default_prompt;
/* Instruct the user */
WriteConsole(
GetStdHandle( STD_OUTPUT_HANDLE ),
prompt,
lstrlen( prompt ),
&count,
NULL
);
FlushConsoleInputBuffer( hstdin );
/* Get a single key RELEASE */
do ReadConsoleInput( hstdin, &inrec, 1, &count );
while ((inrec.EventType != KEY_EVENT) || inrec.Event.KeyEvent.bKeyDown);
/* Restore the original console mode */
SetConsoleMode( hstdin, mode );
return inrec.Event.KeyEvent.wVirtualKeyCode;
}
Finally, possible portable way is:
#include <iostream>
#include <limits>
void PressAnyKeyToContinue()
{
cout << "Press any key to continue...";
cin.ignore();
cin.get();
}
More on the topic: http://www.cplusplus.com/forum/articles/7312/
Upvotes: 1