Read only 1 character in C ++

Possible duplicate:
How does std :: iostream work?

This may sound funny, but how can I read one char from cin in C ++ (until the enter key is pressed, only one character)? I've tried operator ->, get (), getchar (), but they all read the whole line.

+3


source to share


3 answers


The _ getche () function does what you want.



+3


source


cin

- buffer input. You want an "unbuffered" input. It may differ on different platforms if you are not working directly with files.

Something like this might help:



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

[EDIT] Remember that using "buffered" v. "un-buffered" is by design and both are legal. The "default" for "buffered input" cin

doesn't make a lot of sense, since the user will "back off" to correct the input line, and you don't want the "noise" to feed your program. (And in general, "buffered input" as from files can be much more efficient.)

+3


source


While this is OS specific, on 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 details .

+2


source







All Articles