问题
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