请确保您使用的是OSX!在OSX上不输入密码钥匙
GCC信息:
使用内置的规格。 目标:i686-apple-darwin11 配置为:/private/var/tmp/llvmgcc42/llvmgcc42-2336.11~28/src/configure --disable-checking --enable-werror --prefix =/Applications/Xcode.app /Contents/Developer/usr/llvm-gcc-4.2 --mandir =/share/man --enable-languages = c,objc,C++,obj-C++ --program-prefix = llvm- --program-transform-name =/^ [cg] [^ .-] * $/s/$/- 4.2/--with-slibdir =/usr/lib --build = i686-apple-darwin11 --enable-llvm =/private/var /tmp/llvmgcc42/llvmgcc42-2336.11~28/dst-llvmCore/Developer/usr/local --program-prefix = i686-apple-darwin11- --host = x86_64-apple-darwin11 --target = i686-apple-darwin11 --with-gxx-include-dir =/usr/include/C++/4.2.1 线程型号:posix gcc版本4.2.1(基于Apple Inc. build 5658)(LLVM build 2336.11.00)
我想要得到一个字符从按键并显示它。我试图在没有Curses库的情况下这样做(将用于Android和OSX等,我不想移植)。基于另一篇文章,我想出了下面....
#include <stdio.h>
#include <termios.h>
#include <time.h>
#include <string.h>
static char ch;
void getkey() {
struct termios orig_term_attr;
struct termios new_term_attr;
/* set the terminal to raw mode */
tcgetattr(fileno(stdin), &orig_term_attr);
memcpy(&new_term_attr, &orig_term_attr, sizeof(struct termios));
new_term_attr.c_lflag &= ~(ECHO|ICANON);
new_term_attr.c_cc[VTIME] = 0;
new_term_attr.c_cc[VMIN] = 0;
tcsetattr(fileno(stdin), TCSANOW, &new_term_attr);
/* read a character from the stdin stream without blocking */
/* returns EOF (-1) if no character is available */
char test = fgetc(stdin);
if(test != -1)
printf("Value is : %c \n",test);
ch = test;
/* restore the original terminal attributes */
tcsetattr(fileno(stdin), TCSANOW, &orig_term_attr);
}
int main()
{
do
{
getkey();
int ch2 = (int) ch;
if(ch2 != -1){
printf("%c \n",ch);
}
}while(1==1);
}
但是,这似乎并没有清除缓冲区,所以当我键入一个则B的C我看到...
aababc
这是目前正在编译并在我的OSX与海湾合作委员会的命令框tect.c运行和./a.out
我想它是ABC
级
你看到什么没有多大意义......你有两个'printf'语句,它们都放置空格和回车。你怎么能通过键入“abc”有这样的输出? –
如果你“不想移植”,编写非常系统特定的代码可能是不可行的。 –
我不想编写系统特定的代码,我会愿意接受更通用的答案。这是我迄今为止所能想到的。最终目标是在问题中要求在任何平台上实时捕获按键。随意回答与我不相似的代码。我把OSX放在标题中纯粹是因为我知道它在ubuntu上工作。 – Jackie