2017-06-07 49 views
0

这是我第一次使用ncurses库。所以,我想使用getch()来获取用户输入的字符(而不是每次都按回车)。但是,当我运行此代码:如何在循环中使用getch()(nCurses)

#include <pthread.h> 
#include <stdio.h> 
#include <curses.h> 

void *userInput() { 
char c; 

while((c = getch()) != '~') { 
    printf("%c\n",c); 
} 

pthread_exit(NULL); 

} 

int main() { 
    cbreak(); 

    pthread_t threads[4]; 

    pthread_create(&threads[0], NULL, userInput, NULL); 

    pthread_exit(NULL); 
} 

它printf很多'?'没有得到任何输入。任何人都可以请帮我理解最新的错误? 谢谢。

编辑:删除死码。

+0

@DavidBowling对不起,我忘了删除它。 –

+0

[为什么getch()返回之前按下任何键?](https://stackoverflow.com/questions/7410447/why-getch-returns-before-press-any-key) – KevinDTimm

+1

那么,你不有任何'WINDOW *',甚至不是'initscr()'('getch()'隐式地在'stdscr'上创建)创建的'stdscr'。我不确定,但我可以很好地想象这是你问题的根源:只要'stdscr'存在,'getch()'就会被使用。 –

回答

0

至少有三个问题的方案:

  • getch总是会返回一个错误,因为你没有用initscrnewterm初始化屏幕。同样,cbreak调用除了返回一个错误外什么也不做。

  • 即使您已初始化屏幕,使用多个线程调用getch也不可预测地工作,因为它不是线程安全的。这是一个常见问题解答:Why does (fill in the blank) happen when I use two threads?

  • printf做了些什么,但混合stdio(printf)和curses无法正常工作。 curses应用程序使用printw

至于打印?,这些-1的报表格式,其预计UTF-8可能会决定他们是不是有效的UTF-8和显示replacement character终端。