如何使用Escape键结束C中的循环 [英] How to use Escape Key to end a Loop in C
问题描述
我只想像这样结束C语言中的do while循环:
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
我认为这是一种方式.
推荐答案
27
是Escape的十进制ASCII值,但是您使用的是八进制字符代码.您应该说27
或'\033'
(对于十六进制,则是'\x1b'
,这是更常见的).假设您的终端允许使用Escape字符,则可能是问题所在.有时它们被用于终端级的魔术,因此被终端吃掉".
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.
此外,请注意,尽管getchar()
命名,但返回int
,不 char
.它也可以返回非字符值EOF
(如果您按 Ctrl + D (在Unix中)),因此需要更大的类型.
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.
这篇关于如何使用Escape键结束C中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!