我永远记不住我是如何做到这一点的,因为它对我来说是非常罕见的。但在C或C++中,从标准输入中读取字符而不等待换行符(按enter)的最佳方法是什么?
同样,理想情况下,它不会将输入字符回显到屏幕上。我只想在不影响控制台屏幕的情况下捕获击键。
发布于 2009-05-26 21:14:31
在Linux (和其他类unix系统)上,这可以通过以下方式完成:
#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);
}
基本上,您必须关闭规范模式(和回显模式以抑制回显)。
发布于 2009-05-26 19:07:25
我在另一个论坛上发现了这一点,同时希望解决同样的问题。我在我发现的基础上对它做了一些修改。它工作得很好。我运行的是OS,所以如果你运行的是Microsoft,你需要找到正确的system()命令来切换到raw和cooked模式。
#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;
}
发布于 2009-01-07 21:37:10
CONIO.H
您需要的函数包括:
int getch();
Prototype
int _getch(void);
Description
_getch obtains a character from stdin. Input is unbuffered, and this
routine will return as soon as a character is available without
waiting for a carriage return. The character is not echoed to stdout.
_getch bypasses the normal buffering done by getchar and getc. ungetc
cannot be used with _getch.
Synonym
Function: getch
int kbhit();
Description
Checks if a keyboard key has been pressed but not yet read.
Return Value
Returns a non-zero value if a key was pressed. Otherwise, returns 0.
libconio http://sourceforge.net/projects/libconio
或
conio.h http://sourceforge.net/projects/linux-conioh的Linux c++实现
https://stackoverflow.com/questions/421860
复制相似问题