Capture characters from standard input without waiting for enter to be pressed
That's not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with stdin
(they are usually line buffered). You can, however use a library for that:
conio available with Windows compilers. Use the
_getch()
function to give you a character without waiting for the Enter key. I'm not a frequent Windows developer, but I've seen my classmates just include<conio.h>
and use it. Seeconio.h
at Wikipedia. It listsgetch()
, which is declared deprecated in Visual C++.curses available for Linux. Compatible curses implementations are available for Windows too. It has also a
getch()
function. (tryman getch
to view its manpage). See Curses at Wikipedia.
I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (I believe that's called "raw mode", as opposed to "cooked mode" - look into man stty
). Curses would handle that for you in a portable manner, if I'm not mistaken.
On Linux (and other unix-like systems) this can be done in following way:
#include <unistd.h>
#include <termios.h>
char getch() {
char buf = 0;
struct termios old = {0};
if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
if (read(0, &buf, 1) < 0)
perror ("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if (tcsetattr(0, TCSADRAIN, &old) < 0)
perror ("tcsetattr ~ICANON");
return (buf);
}
Basically you have to turn off canonical mode (and echo mode to suppress echoing).
I found this on another forum while looking to solve the same problem. I've modified it a bit from what I found. It works great. I'm running OS X, so if you're running Microsoft, you'll need to find the correct system() command to switch to raw and cooked modes.
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
// Output prompt
cout << "Press any key to continue..." << endl;
// Set terminal to raw mode
system("stty raw");
// Wait for single character
char input = getchar();
// Echo input:
cout << "--" << input << "--";
// Reset terminal to normal "cooked" mode
system("stty cooked");
// And we're out of here
return 0;
}