getch not reading keyboard input

395 Views Asked by At

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.

1

There are 1 best solutions below

1
algrebe On BEST ANSWER

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;
}