等待按键,但自动启动后的时间c++

Wait for key press but auto-start after time C++

本文关键字:时间 c++ 自动启动 等待      更新时间:2023-10-16

我在其他语言中看到过这个问题的答案,但在c++中没有。我怎样才能让程序等待用户按下Enter或其他类似的键,但只要没有输入一个键,它就会在设定的时间段后自动继续运行?我需要基本的代码,我是一个初学者。我知道sin。get();或系统("暂停");将等待一个键并休眠(x秒);或Sleep(x毫秒);(使用"windows.h"库)将暂停程序,但我如何同时获得两者?

在windows中,您可以使用GetAsyncKeyState()轮询键盘的当前状态。然后,您可以使用Sleep()休眠一定数量的毫秒。把这两者结合起来,你就可以做出你想要的东西:

    int keyToWaitFor = VK_SPACE;
    int count = 0;
    int maxcount = 500;
    for(int a = 0; a < maxcount; a++){
        if (GetAsyncKeyState(keyToWaitFor)!=0){
            break;
        }
        Sleep(5);
    }

既然你显然想在Windows上这样做,那就相当简单了。

首先打开控制台的句柄,例如GetStdHandle。然后,当您想要执行读取操作时,在该句柄上调用WaitForSingleObject,并指定超时值。检查退货单。如果返回值是WAIT_OBJECT_0,这意味着您有一些输入,您可以使用(例如)ReadConsoleInput读取。如果返回值为WAIT_TIMEOUT,则表示没有输入,因此您可以做任何您想做的事情。

对于conio.h,您可以等待kbhit()getch()的按键,并使用a等待20秒计时器while循环,while( key==0 && (time_to_wait < secs) )

#include <iostream>
#include <cstdio>
#include <ctime>
#include <conio.h>
#include <windows.h>
using namespace std;
int key=0;
bool quit=false;
void check_if_keypressed();
void gotoxy(int x, int y);
void clrscr();

int main() 
{
    clock_t start;
    double time_to_wait;
    double secs=10;
    gotoxy(1, 2);
    cout<<"Press any key to continue or wait 20 seconds:  n ";
    start =  clock();
    while( key==0 && (time_to_wait < secs) )
    {
        check_if_keypressed();
        time_to_wait = (  clock() - start ) / (double) CLOCKS_PER_SEC;
    //  proceed with whatever here


        gotoxy(1, 23);
        cout<<"countdown: "<< secs-time_to_wait <<" n ";
    }
    //  proceed with whatever here
    //  while( key!=27)
    //  {
    //    check_if_keypressed();
    //    do_other_stuff();
    //  }

    return 0;
}
void check_if_keypressed()
{
   if( kbhit() ) key=getch();
   switch(key)
   {
      case 27:
           quit=true;
       break;
   }
}

void gotoxy(int x, int y)
{
    COORD coord;
    coord.X = x; coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
    return;
}
void clrscr()
{
    COORD coordScreen = { 0, 0 };
    DWORD cCharsWritten;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    DWORD dwConSize;
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleScreenBufferInfo(hConsole, &csbi);
    dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
    FillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);
    GetConsoleScreenBufferInfo(hConsole, &csbi);
    FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
    SetConsoleCursorPosition(hConsole, coordScreen);
    return;
}