How can "Esc" button exits the program?

This is a discussion on How can "Esc" button exits the program? within the C Programming forums, part of the General Programming Boards category; Hello,
How can I exit a C program by pressing escape key? what are the statements of pressing or hitting ...

You need to look into ASCII. The ASCII value of escape is 27 and you can compare that if the input is stored into a char.

Could you demonstrate how one would do this in practice? For example, try to get the following program to output the result `27' by pressing Escape at the terminal. Hint: it won't work.

Code:

int main(void)
{
int c = getchar();
printf("%d\n", c);
return 0;
}

Why? Because when you type at the terminal window, the terminal is in "cooked" mode and the program won't see any characters that you typed until you press enter. For example, when you press backspace and delete, these are not even seen by the standard input/output system. The same is true for the "Escape" key. In fact, the behaviour of this and other keys in cooked mode depends on the operating system.

To answer the question, I would recommend using a lower level layer like curses, which can put the terminal into raw mode (keypad mode, in curses terminology). Then use getch() to read the keycode. If it was escape, exit the program. Otherwise, use ungetch() and resume normal operation.

My appologies I guess one should test a solution before posting it. I use too many high level libraries that sometimes I forget I haven't tested all processes in the low level languages. Thank you for the correction.