2

请确保您正在使用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);
}

但这似乎并没有清除缓冲区,所以当我输入 a 然后 b 时,我看到了 c...

aababc

目前正在使用命令 gcc tect.c 和 ./a.out 在 My OSX 机器上编译和运行

我希望它是 abc

4

1 回答 1

1

您的代码有效,但您打印了两次字符:

printf("Value is : %c \n",test);
printf("%c \n",ch);

我自己试过:

Value is : a 
a 
Value is : b 
b 
Value is : c 
c 
Value is : d 
d 

顺便说一句,您不应该使用全局变量,而是返回键......

于 2013-07-01T17:21:17.793 回答