我想在控制台应用程序中完成以下任务:
- 如果用户输入一个字符,应用程序将执行以下操作
相应的任务。例如,如果用户输入
1
, 该程序
如果用户输入,将执行任务 1q
,程序将退出;
- 如果用户没有输入任何内容,程序将每隔10秒执行一次默认任务(时间不必很严格)。
这是我的代码:
#include <stdio.h>
#include <time.h>
char buff[64];
char command;
while(command != 'q')
{
begin:
printf(">> ");
scanf("%s", buff);
command = buff[0];
switch (command)
{
case '1':
// task 1 code will be added here;
break;
case '2':
// task 2 code will be added here;
break;
case 'q':
printf("quit the loop.\n");
break;
}
// wait for 10 seconds;
Sleep(10000);
// default task code will be added here;
if(command != 'q')
{
goto begin;
}
}
但问题是程序会陷入scanf()
如果没有输入字符,则函数永远等待输入字符。所以我想知道如何跳过scanf()
一定时间后,我的意思是,例如,如果1秒后没有输入,程序可以继续执行,从而完成上面列出的第二件事。
如果重要的话,平台是Windows。
I've removed the semicolon after the while()
it was an obvious mistake.
尝试使用 select() 函数。然后你可以等待 10 秒,直到你可以从 stdin 读取而不会阻塞。如果 select() 返回零,则执行默认操作。
我不知道这是否适用于 Windows,这是 POSIX 标准。如果你碰巧在unix/linux上开发,请尝试man select
我刚刚使用 select 编写了一个工作示例:
#include <stdlib.h>
#include <stdio.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#define MAXBYTES 80
int main(int argc, char *argv[])
{
fd_set readfds;
int num_readable;
struct timeval tv;
int num_bytes;
char buf[MAXBYTES];
int fd_stdin;
fd_stdin = fileno(stdin);
while(1) {
FD_ZERO(&readfds);
FD_SET(fileno(stdin), &readfds);
tv.tv_sec = 10;
tv.tv_usec = 0;
printf("Enter command: ");
fflush(stdout);
num_readable = select(fd_stdin + 1, &readfds, NULL, NULL, &tv);
if (num_readable == -1) {
fprintf(stderr, "\nError in select : %s\n", strerror(errno));
exit(1);
}
if (num_readable == 0) {
printf("\nPerforming default action after 10 seconds\n");
break; /* since I don't want to test forever */
} else {
num_bytes = read(fd_stdin, buf, MAXBYTES);
if (num_bytes < 0) {
fprintf(stderr, "\nError on read : %s\n", strerror(errno));
exit(1);
}
/* process command, maybe by sscanf */
printf("\nRead %d bytes\n", num_bytes);
break; /* to terminate loop, since I don't process anything */
}
}
return 0;
}
注意:下面的 poll() 示例也可以,没有问题。对于其余部分,我选择将可用字节读入缓冲区(最多 MAXBYTES)。之后可以对其进行扫描。 (scanf() 只是不太适合我的朋友,但这是个人品味问题)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)