Search code examples
cncursescurses

why should I use getch() here?


I'm trying to use ncurses and play with it, so I can make an interface for a program later. In the following code, why do I have to use getch()? If I don't put getch(), it doesn't work. How can I avoid using getch()? Thanks!

#include <ncurses.h>
#include <string.h>

int     main()
{
  int       row;
  int       col;

  initscr();
  getmaxyx(stdscr, row, col);
  mvprintw(row / 2, col / 2, "%s\n", "salut");
  refresh();
  getch();
  endwin();
  return (0);
}

Solution

  • If you want to see the results of the mvprintw on the screen, you have to refresh the screen (done), but also leave the results on the screen long enough to see them. If the terminal description uses the alternate screen feature (e.g., of xterm), then that endwin call will switch back to the normal screen, hiding the results from the ncurses output.

    Calling getch stops the program long enough to see the results.

    The endwin call is needed to restore the terminal modes. While (n)curses is in "screen mode", it has set the terminal (your keyboard) to "raw" mode, to allow it to read all characters. If you do not call endwin before exiting the program, you will have to reset your terminal, e.g.,

    stty sane
    

    ending with controlJ.

    If you do not want the screen to clear in the program, your terminal description has to not do that (as noted in the FAQ). Aside from that, the simple display/exit scenario described can be done using the ncurses function filter (there is an example in ncurses-examples, but it does not account for the alternate screen).

    Further reading: