按下某个键时,如何退出无限循环?目前我正在使用getch,但它会立即开始阻塞我的循环,因为没有更多的输入可供读取。
user196106
问问题
29402 次
5 回答
6
如果您仍然使用getch()
from conio.h
,请尝试使用kbhit()
。请注意,实际上 -getch()
和kbhit()
-conio.h
都不是标准 C。
于 2011-07-18T10:17:37.877 回答
3
如果按下任何键,函数kbhit()
fromconio.h
返回非零值,但它不会像getch()
. 现在,这显然不是标准的。但是由于您已经在使用getch()
from conio.h
,我认为您的编译器具有此功能。
if (kbhit()) {
// keyboard pressed
}
来自维基百科,
conio.h 是旧的 MS-DOS 编译器中用于创建文本用户界面的 C 头文件。The C Programming Language 一书中没有描述它,它不是 C 标准库、ISO C 的一部分,也不是 POSIX 要求的。
大多数面向 DOS、Windows 3.x、Phar Lap、DOSX、OS/2 或 Win32 1的 C 编译器都有这个头文件,并在默认 C 库中提供相关的库函数。大多数面向 UNIX 和 Linux 的 C 编译器没有这个头文件,也不提供库函数。
于 2011-07-18T10:18:35.080 回答
2
我建议你仔细阅读这篇文章。
于 2011-07-18T10:19:42.157 回答
2
如果不想使用非标准、非阻塞的方式又不失优雅的退出。使用信号和Ctrl+C以及用户提供的信号处理程序进行清理。像这样的东西:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
/* 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;
}
于 2017-12-27T12:14:16.387 回答
1
// 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();
}
于 2016-03-14T12:22:03.683 回答