0

This is my first time using ncurses library. So, I wanted to use getch() to get a character as it is typed by the user (without pressing return every time). However, when I run this code:

#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);
}

It printf lots of '?'s without getting any input. Could anyone please help me understand whats wrong? Thank you.

EDIT: removed dead code.

  • @DavidBowling Sorry, I forgot to remove it. – Sankait Laroiya Jun 07 '17 at 19:38
  • Possible duplicate of [Why getch() returns before press any key?](https://stackoverflow.com/questions/7410447/why-getch-returns-before-press-any-key) – KevinDTimm Jun 07 '17 at 19:43
  • 1
    Well, you don't have any `WINDOW *`, not even the `stdscr` which is created by `initscr()` (`getch()` implicitly works on `stdscr`). I'm not sure, but I could well imagine that this is the source of your problem: `getch()` is intended to be used as long as `stdscr` exists. –  Jun 07 '17 at 20:57

1 Answers1

0

There are at least three problems with the program:

  • getch will always return an error because you did not initialize the screen with initscr or newterm. Likewise, the cbreak call does nothing except return an error.

  • even if you initialized the screen, calling getch with multiple threads will not work predictably because it is not thread-safe. It's an FAQ: Why does (fill in the blank) happen when I use two threads?

  • the printf does something, but mixing stdio (printf) and curses does not work as you'd like. Use printw for curses applications.

As for printing ?, those -1's sent to a terminal which expects UTF-8 would likely decide they're not valid UTF-8 and display the replacement character.

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105