gpt4 book ai didi

c - 你如何编写一个 C 程序来通过按键递增一个数字并每秒自动递减它?

转载 作者:可可西里 更新时间:2023-11-01 12:30:34 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,其中的数字从 0 开始,但是当您按下任意键时,它会递增 1。如果没有按下任何键,它会每秒递减 1,直到达到 0。每个增量或减量都显示在控制台窗口上。

我的方法的问题是在我按下一个键之前没有任何反应(也就是说,它检查是否使用 getch() 按下了任何东西)。我如何检查没有按下任何东西?当然,!getch() 不起作用,因为要使其起作用,它仍然需要检查按键,这会使目的本身无效。

操作系统:Windows 10 企业版,IDE:代码:: block

void main()
{
int i, counter = 0;
for (i = 0; i < 1000; i++)
{
delay(1000);
// if a key is pressed, increment it
if (getch())
{
counter += 1;
printf("\n%d", counter);
}
while (counter >= 1)
{
if (getch())
{
break;
}
else
{
delay(1000);
counter--;
printf("\n%d", counter);
}
}
}
}

最佳答案

以下短程序既不需要 ncurses 也不需要线程。但是,它确实需要更改终端属性 - 使用 tcsetattr()。这将适用于 Linux 和类 Unix 系统,但不适用于 Windows - 它不包含 termios.h 头文件。 (如果您对该主题感兴趣,请参阅 this post。)

#include <stdio.h>
#include <string.h>
#include <termios.h>

int main(int argc, char *argv[]) {
struct termios orig_attr, new_attr;
int c = '\0';
// or int n = atoi(argv[1]);
int n = 5;

tcgetattr(fileno(stdin), &orig_attr);
memcpy(&new_attr, &orig_attr, sizeof(new_attr));
new_attr.c_lflag &= ~(ICANON | ECHO);
new_attr.c_cc[VMIN] = 0;
// Wait up to 10 deciseconds (i.e. 1 second)
new_attr.c_cc[VTIME] = 10;
tcsetattr(fileno(stdin), TCSANOW, &new_attr);

printf("Starting with n = %d\n", n);
do {
c = getchar();
if (c != EOF) {
n++;
printf("Key pressed!\n");
printf("n++ => %d\n", n);
} else {
n--;
printf("n-- => %d\n", n);
if (n == 0) {
printf("Exiting ...\n");
break;
}
if (feof(stdin)) {
//puts("\t(clearing terminal error)");
clearerr(stdin);
}
}
} while (c != 'q');

tcsetattr(fileno(stdin), TCSANOW, &orig_attr);

return 0;
}

重点是

new_attr.c_lflag &= ~(ICANON | ECHO);

使终端脱离规范模式(并禁用字符“echo”),

new_attr.c_cc[VMIN] = 0;

将其置于轮询(而不是“阻塞”)模式,并且

new_attr.c_cc[VTIME] = 10;

指示程​​序等待输入 10 分秒。

更新(2019-01-13)

  • 添加clearerr(stdin)以清除stdin上的EOF(在某些平台上似乎是必需的)

关于c - 你如何编写一个 C 程序来通过按键递增一个数字并每秒自动递减它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52715808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com