while循环中,如何实现按键后自动退出?
如题一个while循环,如果没有按键输入,就一直循环执行语句,直到我按键盘,才退出循环。
系统为Linux,不是windows。
[解决办法]
1、设置一个循环标志。主进程中进行循环并且在每次循环中检查循环标志决定是否继续,线程中检测按键输入后改变该标志
2、主进程中进行按键检测,线程用于循环操作,主进程检测到按键后关闭循环线程
3、在循环中对键盘缓冲区进行扫描,用于判断是否有按键信息
以上是我在windows下常用的几种方式,LINUX仅供参考
[解决办法]
linux不太清楚 windows可以用API函数调用看看缓冲区时候有键盘中断
linux应该也差不多就是看看有没有键盘中断
[解决办法]
- C/C++ code
char a = ' ';do{//your coding}while((c = getch()) == 'n')
[解决办法]
可以用一下方法实现:
void main()
{
bool end=false;
while(end)
{
....
....
if(keypdown())
{
end=true;
}
}
}
bool keydown()
{
... //判断是否是指定的按键按下
...
}
[解决办法]
do
{
printf("hello");
}while(getch() == ' ')
[解决办法]
[解决办法]
- C/C++ code
/* 判断是否有按键按下 */int kbhit(void){ struct timeval tv; struct termios old_termios, new_termios; int error; int count = 0; tcgetattr(0, &old_termios); new_termios = old_termios; new_termios.c_lflag &= ~ICANON; new_termios.c_lflag &= ~ECHO; new_termios.c_cc[VMIN] = 1; new_termios.c_cc[VTIME] = 0; error = tcsetattr(0, TCSANOW, &new_termios); tv.tv_sec = 0; tv.tv_usec = 100; select(1, NULL, NULL, NULL, &tv); error += ioctl(0, FIONREAD, &count); error += tcsetattr(0, TCSANOW, &old_termios); return error == 0 ? count : -1;}/*** system_mode* reset the system to what it was before input_mode was* called*/void system_mode(void){ if (ioctl(0, TCSETA, &term_orig) == -1) { return; } fcntl(0, F_SETFL, kbdflgs);}/*** input_mode* set the system into raw mode for keyboard i/o* returns 0 - error* 1 - no error*/int input_mode(void){ struct termio term; if (ioctl(0, TCGETA, &term) == -1) { return 0; } (void) ioctl(0, TCGETA, &term_orig); term.c_iflag = 0; term.c_oflag = 0; term.c_lflag = 0; term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 0; if (ioctl(0, TCSETA, &term) == -1) { return 0; } kbdflgs = fcntl(0, F_GETFL, 0); int flags = fcntl(0, F_GETFL); flags &= ~O_NDELAY; fcntl(0, F_SETFL, flags); return 1;}/*** getch* read a single character from the keyboard without echo* returns: the keypress character */int getch(void){ unsigned char ch; input_mode(); while(read(0, &ch, 1) != 1); system_mode(); return (ch);}
[解决办法]
/* 全局变量 */
static struct termio term_orig;
static int kbdflgs;
忘记了这个,补上
[解决办法]
kbhit和getch配合,和dos/windows一样
[解决办法]
kbhit()、getch()是非ANSI C标准的函数,但是许多编译器都有其实现。若不考虑代码移植问题,可以用kbhit、getch函数检查任意键。getchar()之类函数必须用回车键。
[解决办法]
getch()会造成执行停顿,必须有用户的键盘输入才能继续执行--忘了说这一句
[解决办法]
不难,linux控制台就可以判断按键,只是没安装起来,所以也不了解,暂时比较忙,也没时间看书
[解决办法]
while循环是一个线程,另外开个线程来监视键盘
[解决办法]
kbhit()、getch()是非ANSI C标准的函数,但是许多编译器都有其实现。若不考虑代码移植问题,可以用kbhit、getch函数检查任意键。getchar()之类函数必须用回车键。
[解决办法]
1、可以像上面说的建立两个线程,一个是你的while 一个是监控键盘输入。
2、linux下有类似windows的键盘钩子,可以获取的键盘输入,注册一个回调进去,到时候直接触发。
[解决办法]
额!!!
linux用libevent吧.
[解决办法]
为什么呢不用信号呢?linux下有键盘中断捕获函数 可以用signal
[解决办法]
[code=C/C++][/code]
void printout(int);
回帖测试 请楼主无视
[解决办法]
do
{
printf("hello");
Sleep(1000);
}while( !_kbhit() );
[解决办法]
又没看懂 诶……