c-等待输入一段时间



程序不等待Enter键被按下,但它将无限期地等待字符被输入和&quot-"标志永远不会出现在屏幕上。如何使程序只等待输入一段时间?

#include <stdio.h>
#include <stdlib.h>
int main(void) {
char c = 'A';
system("stty raw"); 
c = getchar();
system("stty cooked");

if (c == 'A')
printf("-n");
else
printf("+n");
return 0;
}

没有标准的方法来做你想做的事情,但stty的使用让我觉得你在使用某种类型的*nix系统。然后你可以使用select(这是一种非常古老的方法(等待输入一段时间。

下面是一个如何等待一秒钟的例子。

#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
int main(void) {
char c = 'A';
int stdinfd = fileno(stdin); // your platform probably has a macro for this
struct timeval timeout = {
.tv_sec = 1, // seconds
.tv_usec = 0 // microseconds
};
fd_set fds; // a set of file descriptors to wait for
FD_ZERO(&fds); // initialize the set
FD_SET(stdinfd, &fds); // put "stdin" in the set to wait for
system("stty raw");
int rv = select(stdinfd + 1, &fds, NULL, NULL, &timeout);
system("stty cooked");
if(rv > 0) { // more than zero file descriptors are ready
c = getchar();
if(c == 'A')
printf("-n");
else
printf("+n");
} else {    // no file descriptors are ready (or there was an error)
puts("timeout");
}
}

阅读您的平台文档,了解如何在不调用system的情况下执行stty rawstty cooked

由于在C中没有标准的方法来做您想做的事情,您可以使用一个库,比如curses库,来做您想要做的事情。curses以这样或那样的形式可用于大多数平台。对于Windows,您可以安装pdcurses。在*nix平台上,它通常已经安装好了。

示例:

#include <curses.h>
#include <stdio.h>
int main(void) {
initscr();     // initialize curses
timeout(1000); // set the input timeout in milliseconds
int ch = getch();
// restore the terminal I/O settings -
// this is usually the last thing in a curses program:
endwin(); 
if(ch == ERR) {
puts("timeout");
} else {
printf("you typed %cn", ch);
}
}

最新更新