简体   繁体   English

当键盘输入无限循环停止时 - C

[英]do while infinite loop stop on keyboard input - C

there is any way to run an infinite cycle that stops only on user input from keyboard without asking every cycle to continue? 有没有办法运行一个无限循环,只停止来自键盘的用户输入而不要求每个循环继续? in a C program (I'm developing a C chat that read the entries with a for(;;) loop and I need to stop it only when the user want to type and send a message) hi all! 在一个C程序中(我正在开发一个C聊天,用for(;;)循环读取条目,我只需要在用户输入并发送消息时才停止它)嗨!

You didn't specify the OS so I will assume some POSIX compliant OS. 您没有指定操作系统,所以我将假设一些符合POSIX的操作系统。

You can use select . 你可以使用select This can be used to block on a set of file descriptors (in your case, stdin) with a finite timeout or indefinite blocking. 这可以用于阻止一组文件描述符(在您的情况下,stdin)具有有限超时或无限阻塞。

My guess is, since this is a chat program, you would also want to do this on some other file descriptor, like your chat tcp socket. 我的猜测是,因为这是一个聊天程序,你也想在其他文件描述符上做这个,比如你的聊天tcp套接字。 So you can test for input on both with one call. 因此,您可以通过一次调用测试两者的输入。

In case of windows console, you should be able to use GetStdHandle and WaitForSingleObject/WaitForMultipleObjects if select does not work for you. 对于Windows控制台,如果select对你不起作用,你应该能够使用GetStdHandle和WaitForSingleObject / WaitForMultipleObjects。

There are a number of ways of doing this in Windows. 在Windows中有很多方法可以做到这一点。 Assuming you're using VC++, the easiest way is probably to use _kbhit() . 假设您正在使用VC ++,最简单的方法可能是使用_kbhit() If you want to use the Win32 API directly instead, you could call GetNumberOfConsoleInputEvents() and see whether the return is non-zero. 如果要直接使用Win32 API,可以调用GetNumberOfConsoleInputEvents()并查看返回值是否为非零。

You could also do an overlapped read, and each time through the loop call WaitForSingleObject with a timeout value of 0. The zero wait means it'll return immediately whether there's input or not. 您还可以执行重叠读取,并且每次通过循环调用WaitForSingleObject时超时值为0.零等待意味着它将立即返回是否有输入。 The return value will tell you whether you have any data: WAIT_TIMEOUT means no data has been read yet, and WAIT_OBJECT0 means you have some data waiting to be processed. 返回值将告诉您是否有任何数据:WAIT_TIMEOUT表示尚未读取任何数据,WAIT_OBJECT0表示您有一些数据等待处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM