[英]Getting key without enter on 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.內部版本5658)(LLVM內部版本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對此文件進行編譯並在“我的OSX”框中運行。
我希望它是abc
您的代碼有效,但是您兩次打印了字符:
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
順便說一句,您不應使用全局變量,而應返回鍵...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.