BowPark
BowPark

Reputation: 1470

ncurses, print and contemporary acquire strings

A program written in C uses ncurses. A while cycle is used to continuously check if a new message is arrived in a queue: if it is, the message is printed on screen and then removed from the queue:

while (condition)
{
if (queue_not_empty)
{
printw(element_from_queue);
refresh();
remove(element_from_queue);
}
}

At the same time, however, the program should be able to acquire an input string from the user and then store it in the array char message[100] through a scanw. But if I put

while (condition)
{
if (queue_not_empty)
{
printw(element_from_queue);
refresh();
remove(element_from_queue);
}
scanw(message);
}

the cycle will stop until the user doesn't type a string and the program will print the new messages of the queue only after a user input. It should not be like this! The queue messages could arrive at any time and should be printed; the user messages could arrive at any time and should be stored into the array.

I would like to avoid the creation of another thread, because ncurses becomes weird with multiple threads. Anyway, I would need two "contemporary" while cycles, one for printing the messages and one for reading the user input.

May there be a solution?

In other words: is it possible with ncurses to print some output and to get some multiple characters input from the user in the same screen, in the same thread?

Upvotes: 0

Views: 485

Answers (1)

Thomas Dickey
Thomas Dickey

Reputation: 54583

ncurses provides functions for reading a single character with a timeout (or even no delay at all). Those are not useful with scanw (which always blocks, waiting for several characters):

  • when using a timeout, getch returns ERR rather than a character when the timeout expires.
  • scanw may use getch internally, but has no way to continue when getch returns ERR.

Rather than block, you can poll for input. If no character is available within a given time interval, your program gives up (for the moment), and does something more useful than waiting for characters. Applications that poll for input can be written to accept characters one at a time, adding them to a buffer until the user presses Enter, and then run sscanf on the completed text.

The regular C sscanf is used (which reads from a string) rather than reading directly from the screen with scanw.

Upvotes: 2

Related Questions