views:

125

answers:

2

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();
    ...
}
+1  A: 
KEY_ENTER == 0x157, '\n' == 0xA

'\n' is the standard ASCII newline, while KEY_ENTER represents a keyboard code. See the PDCurses code.

For more information, you should post the relevant part of your code.

Matthew Flaschen
But how come it didn't work when I tried KEY_ENTER?
wrongusername
Because after you pressed enter, `key == '\n'`. It can't equal two things at once. You should post your code if you want more help.
Matthew Flaschen
I have posted my code just now
wrongusername
I don't get how `key` being an `int` (so it can't equal `'\n'` at any time, right?) does not equal `KEY_ENTER` after a key is pressed, but `(char)key` does equal `\n`
wrongusername
Yes, an int can equal a character constant. Try `int c = 10; if(c == '\n') { doSomething(); }`
Matthew Flaschen
Thanks for clearing that up!
wrongusername
+1  A: 

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.

Heath Hunnicutt
what are the benefits of using `wgetch()`?
wrongusername
getch() is a macro which conflicts with the C standard function of that name. wgetch(WINDOW *) won't conflict. You can make your own replacement macro if you like the lack of argument, perhaps call it getkey() or getcursed().
Heath Hunnicutt
Another problem with `getch()` and using int for chars is unicode. You can't represent all possible characters a user might input in an int, and getch() is from ASCII days.
Stephen P
@Stephen - I thought so at first, but I'm not sure what curses getch() would return.
Heath Hunnicutt