C 使用键盘输入循环时暂停
当我按下e或w或我选择的任何键时,是否有任何方法可以暂停我的无限while循环,让用户输入值并再次恢复循环C 使用键盘输入循环时暂停,c,while-loop,C,While Loop,当我按下e或w或我选择的任何键时,是否有任何方法可以暂停我的无限while循环,让用户输入值并再次恢复循环 while(1){ //some code //i want to pause this loop whenver i want with a key and resume again } 这取决于您使用的控制台 如果您使用的是WindowsShell,我会这样写 #include <stdio.h> #include <stdlib.h> #include &
while(1){
//some code
//i want to pause this loop whenver i want with a key and resume again
}
这取决于您使用的控制台 如果您使用的是WindowsShell,我会这样写
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
void checkKey() {
int key;
if (_kbhit()) {
key =_getch();
if (key == 'w' || key == 'e') {
getch();
}
}
}
int main(int argc, char **argv) {
printf("loop is doing something");
while(1) {
printf(".");
Sleep(100);
checkKey();
}
return 0;
}
_kbhit检查是否按下了某个键,然后getch暂停程序,直到按下任何键
对于unix终端实现,该代码将完全不同。在这种情况下,您应该阅读有关termio和非阻塞模式的非常困难的内容
如果您正在编写某种图形应用程序,那么您必须检查正在使用的库的密钥处理文档。例如,用于OpenGL GLUT库的glutKeyboardFunc的功能
我希望这有帮助。如果您不懂什么,请随时询问。我想随时暂停,更改一些值,然后继续我认为您正在寻找同步原语锁/信号量等。I/O线程可以获取一个锁,从而禁用循环执行,循环必须等待锁释放。输入valuevoid checkKey后,它不允许我再次暂停{int key;if{kbhit{key=\getch;switchkey{case'e':scanf%.2f,&harvest;break;case'w':scanf%.2f,&harvest;break;case'p':scanf%7d,&maxPopu;break;case'o':scanf%f,&growth;break;case'l':scanf%f,&growth;break;case'q':exit0;} } }