C在按键上退出无限循环

当按下某个键时,如何退出无限循环? 目前我正在使用getch,但它会尽快开始阻止我的循环,因为没有更多的输入要读取。

我建议你去看看这篇文章。

没有ncurses的循环中非阻塞用户输入。

如果你正在使用conio.h getch() ,请尝试使用kbhit() 。 请注意,事实上getch()kbhit()conio.h都不是标准C.

如果按下任何键, conio.h的函数kbhit()将返回非零值,但它不像getch()那样阻塞。 现在,这显然不是标准的。 但是,由于您已经在使用conio.h getch() ,我认为您的编译器具有此function。

 if (kbhit()) { // keyboard pressed } 

来自维基百科 ,

conio.h是旧的MS-DOS编译器中用于创建文本用户界面的C头文件。 它没有在C编程语言书中描述,它不是C标准库的一部分,ISO C也不是POSIX所要求的。

大多数针对DOS,Windows 3.x,Phar Lap,DOSX,OS / 2或Win32 1的 C编译器都有此标头,并在默认C库中提供相关的库函数。 大多数针对UNIX和Linux的C编译器没有此标头,也没有提供库函数。

 // Include stdlib.h to execute exit function int char ch; int i; clrscr(); void main(){ printf("Print 1 to 5 again and again"); while(1){ for(i=1;i<=5;i++) printf("\n%d",i); ch=getch(); if(ch=='Q')// Q for Quit exit(0); }//while loop ends here getch(); } 

如果您不想使用非标准,非阻塞方式而且优雅退出。 使用信号和Ctrl + C与用户提供的信号处理程序进行清理。 像这样的东西:

 #include  #include  #include  /* Signal Handler for SIGINT */ void sigint_handler(int sig_num) { /* Reset handler to catch SIGINT next time. Refer http://en.cppreference.com/w/c/program/signal */ printf("\n User provided signal handler for Ctrl+C \n"); /* Do a graceful cleanup of the program like: free memory/resources/etc and exit */ exit(0); } int main () { signal(SIGINT, sigint_handler); /* Infinite loop */ while(1) { printf("Inside program logic loop\n"); } return 0; }