BowPark BowPark -4 years ago 106
Linux Question

ncurses and getch - Handling erase and arrow characters

In a C program under Linux and

ncurses
, I need to acquire characters from the keyboard (so, from the user) and to store them into a string, which is considered complete only when the user presses Enter. At the same time, however, I need to display a screen echo for the user, so that he can see what he is writing and he can correct some typos, if necessary.

My bunch of code is working, but it can't handle the erase and arrow characters.

In this question a solution is provided to correctly store the string, when Backspace or Del are pressed. But what solution could be choosen in order to display a correct screen echo, even considering the arrow keys?

My code is essentially:

while(1)
{
if (getch() =! ERR)
// store the character into an array
if (getch() == 10)
// terminate the string and print it on screen
}


The characters are acquired through a
getch()
one by one. Like in the linked question, if I don't use
noecho()
and I press Backspace, the sequence
^?
is displayed instead of removing the previous character from the screen. If I use
noecho()
, the program should show real-time to the user what's happening. Should I re-print the string at every
while
cycle? It would be cumbersome.

So, how can I correctly display to the user what's happening?

Answer Source

If the OP's program used the keypad() function, then left-cursor (arrow) and the erase key would have the same effect. getnstr does not support inline editing (moving the cursor within the line). (Incidentally, other implementations of curses do nothing with cursor-keys).

As an example of a program which does support inline-editing, dialog is useful (it works with UTF-8). On the other hand, because it stores the responses as a plain character string, it is more complicated, say, than something explicitly written to use wget_wch.

cdk does not handle UTF-8.

ncurses does not provide a more interesting function because:

  • that functionality is already in the form library
  • it does not qualify as an extension because one can readily develop various functions of this sort without knowing the library's internals.

Recently there was a related question (for blocking I/O) in ncurses, print and contemporary acquire strings (again, dialog does that).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download