【问题标题】:How to define a certain time for the getch() function in C?如何在 C 中为 getch() 函数定义某个时间?
【发布时间】:2020-06-01 19:27:39
【问题描述】:

我试图让 C 语言的函数 getch() 在 Windows 中只工作几秒钟。

#include <stdio.h>
#include <windows.h>
int main()
{
    int v1, v2;
    v1=getch();//I want this getch to only be activated for a few seconds
    printf("Example");//That to activate the next function, even if the person reading this programm doesn't click in any key
    return 0;
}

【问题讨论】:

  • 你能让stdin 无缓冲吗? stackoverflow.com/questions/10247591/…
  • @FiddlingBits 与 OP 的要求并不真正相关。
  • Windows - 你可以在超时循环中检查kbhit() - 比如使用clock()。不需要特殊步骤,它是为您提供的,因此您不必提交阻塞功能
  • @MarcoBonelli 我不清楚。我的意思是您可以循环旋转并在时间到期时break。 getch (stdin) 的问题在于它默认会阻塞,对吧?
  • @FiddlingBits 确切地说,它不是“默认情况下”,它只是在没有可用数据时阻止,就是这样。

标签: c windows codeblocks getch


【解决方案1】:

您需要使用 ncurse 库并调用:

  • initscr 或 newterm 来初始化屏幕
  • 超时,具有正延迟。否则,它不会被阻塞。

阅读更多here

【讨论】:

    【解决方案2】:

    在提交阻塞函数getch() 之前,您可以使用kbhit() 来测试是否已按下某个键。下面的循环使用clock() 来检查超时。

    #include <conio.h>
    #include <stdio.h>
    #include <ctype.h>
    #include <time.h>
    
    #define TIMEOUT 5   // seconds
    
    int main(void)
    {
        clock_t tstart = clock();
        int v1 = 'y';                   // default key press
        while((clock() - tstart) / CLOCKS_PER_SEC < TIMEOUT) {
            if(kbhit()) {
                v1 = getch();
                break;
            }
        }
        if(tolower(v1) == 'y')
            printf("Example\n");
        return 0;
    }
    

    它在游戏中特别有用,你不想坐在那里等待按键,然后使用起来就不是那么简单了。当您按下功能键或光标键时getch() 返回两个连续字符,第一个是必须检查的“转义”值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      相关资源
      最近更新 更多