Jack
Jack

Reputation: 16724

How to use getch() (from curses library)?

Consider this code:

if(initscr() == NULL) ERROR("Cannot start ncurses mode.\n");

    keypad(stdscr, TRUE);

    cbreak();

    int reply = getch(); 

    if(reply == 'y')
        printw("yes!\n");
    else if(reply == 'n')
        printw("no!\n");
    else
        printw("invalid answer!\n");

    refresh();

    endwin();

Independent of key that I type, the program closes without print any message.

Can someone explain the behavior of this program? Thanks in advance.

Upvotes: 1

Views: 1131

Answers (2)

hymie
hymie

Reputation: 2058

If you insert a sleep(5) in between your refresh() and your endwin(), you should see better results. At least, I do.

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263197

You call printw() to print one of three messages, then refresh() to cause the message to be displayed. So far, so good.

You then immediately call endwin(), which (depending on your termcap/terminfo settings) will likely clear the screen.

Chances are the message is actually displayed; it just doesn't stay on the screen long enough for you to read it.

Try adding a delay or another getch() call after the refresh() call.

Upvotes: 2

Related Questions