c++ccursesgetchkeyboard-input

getch not reading keyboard input


Trying to get user input for a simple terminal game. I am on Mac OS.

#include <stdio.h>
#include <curses.h>
#include <iostream>

int main()
{
    int ch;
    while (ch != 113)
    {
        ch = getch();
        std::cout << ch << std::endl;
    }

    return 0;
}

In this example, I'm trying to simply print my keystrokes, but ch = getch() doesn't seem to do anything. It doesn't wait for a keypress and std::cout << ch << std::endl just prints -1 repeatedly. Can't figure out what I'm doing wrong here.


Solution

  • You need to first call initscr before any other curses functions. http://www.cs.ukzn.ac.za/~hughm/os/notes/ncurses.html

    #include <stdio.h>
    #include <curses.h>
    #include <iostream>
    
    int main()
    {
        int ch;
        initscr(); // <----------- this
        while (ch != 113)
        {
            ch = getch();
            std::cout << ch << std::endl;
        }
    
        return 0;
    }