Search code examples
cloopsgetch

How to use Escape Key to end a Loop in C


I just want to end a do while loop in C like this:

#include <stdio.h>
#include <stdlib.h>

main()
{
    char exit;
    do{
        printf("PLEASE INSERT OPTION:");
        exit = getchar();
    }while(exit != '\027');

}//main

I think it is kind of this way.


Solution

  • 27 is the decimal ASCII value for Escape, but you use an octal character code. You should say 27, or '\033' (or '\x1b' for hex which is more common). This might be the problem, assuming your terminal lets through the Escape character. Sometimes they're used for terminal-level magic, and thus "eaten" by the terminal.

    Also, please note that getchar(), despite its name, returns int and not char. It can also return the non-character value EOF (if you hit Ctrl+D (in Unix)) so a larger type is needed.