Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you're on Windows, you can use <code>kbhit()</code> which is part of the Microsoft run-time library. If you're on Linux, you can implement <code>kbhit</code> thus (<a href="http://cboard.cprogramming.com/c-programming/63166-kbhit-linux.html" rel="noreferrer">source</a>):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;termios.h&gt; #include &lt;unistd.h&gt; #include &lt;fcntl.h&gt; int kbhit(void) { struct termios oldt, newt; int ch; int oldf; tcgetattr(STDIN_FILENO, &amp;oldt); newt = oldt; newt.c_lflag &amp;= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &amp;newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &amp;oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if(ch != EOF) { ungetc(ch, stdin); return 1; } return 0; } </code></pre> <p><strong>Update:</strong> The above function works on OS X (at least, on OS X 10.5.8 - Leopard, so I would expect it to work on more recent versions of OS X). This <a href="https://gist.github.com/1864660" rel="noreferrer">gist</a> can be saved as <code>kbhit.c</code> and compiled on both Linux and OS X with</p> <pre><code>gcc -o kbhit kbhit.c </code></pre> <p>When run with</p> <pre><code>./kbhit </code></pre> <p>It prompts you for a keypress, and exits when you hit a key (not limited to Enter or printable keys).</p> <p><strong>@Johnsyweb</strong> - please elaborate what you mean by "detailed canonical answer" and "all the concerns". Also, re "cross-platform": With this implementation of <code>kbhit()</code> you can have the same functionality in a C++ program on Linux/Unix/OS X/Windows - which other platforms might you be referring to?</p> <p><strong>Further update for @Johnsyweb:</strong> C++ applications do not live in a hermetically sealed C++ environment. A big reason for C++'s success is interoperability with C. All mainstream platforms are implemented with C interfaces (even if internal implementation is using C++) so your talk of "legacy" seems out of place. Plus, as we are talking about a single function, why do you need C++ for this ("C with classes")? As I pointed out, you can write in C++ and access this functionality easily, and your application's users are unlikely to care <em>how</em> you implemented it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload