Search code examples
c++newlinecursespdcurses

KEY_ENTER vs '\n'?


When I'm using PDcurses and I try to have a while loop exit when the enter key is pressed with while(key != KEY_ENTER), the while loop never exits. However, when I try to have the same loop exit with while((char)key != '\n'), it exits successfully whenever I pressed enter. Why does '\n' work and not KEY_ENTER?

btw, key is an int

and I hope this is the relevant few lines of the code:

int key;
while((char)key != '\n') {
    key = getch();
    ...
}

Solution

  • getch() is a function defined by the ANSI C standard for the C runtime library.

    On most systems, such as Windows, Linux, etc., this function is implemented to return '\n' when the user pressed Enter. For Comparison, on Windows the key-press itself (of Enter) might be represented as the key-code VK_ENTER.

    PDCurses is translating the key codes to ASCII values for you.

    You can get the key values you want if you first call the PDCurses functions raw(); nonl();. Also, you should probably use wgetch() for new code.