How to use Escape Key to end a Loop in C

99封情书 提交于 2019-12-12 04:53:50

问题


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.


回答1:


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.




回答2:


I've just found the problem, look this code:

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


main()
{
int exit;
do{
     printf("PLEASE INSERT OPTION:");
exit = getch();

}while(exit != 27);

}//main

That worked. Thanks for the help. @MichaelWalz @DrewMcGowen @2501 @unwind



来源:https://stackoverflow.com/questions/26783701/how-to-use-escape-key-to-end-a-loop-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!