|
Question as follows:
Adam: because it is not often used, so I can never remember how to implement this function. In the C / C ++, and not to the next line (press enter) is obtained from standard input and what is the best method of character is it?
Also, if the characters do not have to type in the screen that is certainly the most perfect, but I just can not imagine been knocked Console (Enter) to get keyboard input.
Some answers:
Best one, from Johannes Schaub - litb:
If only pure C ++, then it is unlikely to meet the portability, because it is largely dependent on the terminal being used, in which the terminal is connected to stdin (usually line buffered). But you can use some libraries to perform this function:
Under 1.Windows compiler is available conio. Use _getch () function so you do not wait for a carriage return character input can be obtained. I do not often use the Windows development environment to develop, but I've seen my classmates just include the header file conio.h ready for use. You can find conio.h in Wikipedia. The above lists getch (), declared as deprecated (deprecated) in in Visual C ++.
2.Linux development environment can be used in curses, it can also be used in Windows-compatible curses implementation. Compared to conio It also has a getch () function. (You can view its manpage by man getch). Similarly, you can also find Curses on Wikipedia.
If you intend to make your program run cross-platform, I recommend you use curses. However, I believe there is something you can use to turn off the function line buffer (I believe it should be called "raw mode", and "processing mode", can be viewed in detail in the man stty). Curses can help you deal with this in cross-terminal cross-platform environment.
Sone of codes:
From Kay:
This code uses kbhit () Check whether the keyboard is pressed, and obtain input characters using getch ().
#include < conio.h>
if (kbhit ()! = 0) {
cout < < getch () < < endl;
}
From Falcon Momot:
Linux (or other UNIX systems) can be achieved in:
#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);
} |
|
|
|