Input to a character, without pressing return key

Here is a piece of code...

1
2
3
char o;
cout << "Is this possible? y/N\t";
cin >> o;


The output would be the question displayed and cursor waiting for input. For example I press 'y'. Then I have to press <Return> to get the input. Then I can perform a switch operation on c.

But I don't want it that way...

1- I want the input just with the keyboard hit, without having to press <Return>.
2- If anyone uses a Linux based OS, he might be familiar with this y/N... The capital "N" means that if nothing is entered, N is the default value... So, if <Return> is pressed instead of 'y'or 'n' I want c to have a value '\n' or ' '.

How can that be accomplished?

For the first part, I knew a function (maybe it was getche()) which would return the key pressed and c = getch() would do both 1st and 2nd of my requirements. But then I stopped using it because someone told me it's not "standard" and might be "dangerous"... Whatsoever, if it is safe and standard to use that function, please remind me that function. If there is another similar function, I would like to know about it. And if no such function exists, is there any other way to do what I wanna do?
There's no standard way to do this. You can use libraries such as Curses or write your own implementation of getch()

Here's an example for Windows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <windows.h>
#include <stdexcept>
using namespace std;

char win_getch()
{
  char c=0;
  DWORD mode, count;
  HANDLE ih = GetStdHandle( STD_INPUT_HANDLE );

  if (!GetConsoleMode( ih, &mode )) // If this is a GUI program, or if GetConsoleMode() fails
      throw runtime_error(
                "This works only inconsole\n");

  SetConsoleMode( ih, mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT) ); // Disable echoing

  ReadConsoleA( ih, &c, 1, &count, NULL);

  SetConsoleMode( ih, mode ); //

  return c;
}


int main() {

char c=win_getch();

}

Oh. Thanks... That is exactly what I needed...
Topic archived. No new replies allowed.