3

Possible Duplicate:
How is std::iostream buffered?

This might sound ridiculous, but how can I read one char from cin in c++ (NOT until enter is pressed, just one character)? I've tried operator >>, get(), getchar(), but all of them reads a whole line.

Community
  • 1
  • 1
Dave
  • 690
  • 4
  • 7
  • 16
  • 1
    All of the methods that you specify read one character from `std::cin`. That character isn't made available from the O/S, however, until ENTER is pressed. – Robᵩ Apr 02 '12 at 18:19
  • 1
    What OS are you using? As Rob said, the OS holds the input until . To get a keyboard event when it happens, you need an OS-specific library. – Adam Shiemke Apr 02 '12 at 18:22
  • @Robᵩ So what you say is that it is not possible to read only one char? All the other languages I know have a function for that. – Dave Apr 02 '12 at 18:23
  • 1
    @Dave - It's not a language problem, it is system specific. I you run your program on a mainframe, the *terminal* will not send the input until you press Enter. C++ cannot do anything about that! – Bo Persson Apr 02 '12 at 18:31

3 Answers3

3

cin is buffered input. You want "unbuffered" input. It can be different on different platforms, unless you work directly with files.

Something like this might help:

http://www.cplusplus.com/forum/beginner/3329/

[EDIT], Remember that use of "buffered" v. "un-buffered" is a design decision, and both are legitimate. The "default" for "buffered-input" on cin makes a lot of sense, as the user will "backspace" to correct the input-line, and you don't want that "clutter" feeding your program. (And, in general, "buffered-input" like from files can be much more efficient.)

charley
  • 5,913
  • 1
  • 33
  • 58
3

The _getche() function does what you want.

Carey Gregory
  • 6,836
  • 2
  • 26
  • 47
  • 2
    Yes, but he didn't ask for portability and he states in his comments above he's using Win7. Also, as Adam Shiemke and Rob pointed out, to get a keyboard event you're going to need an OS-specific function. – Carey Gregory Apr 02 '12 at 18:30
2

While this is OS specific, in UNIX-like operating systems you can use the termios interface to disable input buffering on the terminal by putting it in non-canonical mode:

termios t;
tcgetattr(STDIN_FILENO, &t);
t.c_lflag &= ~ICANON;
tcsetattr(STDIN_FILENO, TCSANOW, &t);

See termios(3) for more details.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324