等待按键,但自动启动后的时间c++
Wait for key press but auto-start after time C++
我在其他语言中看到过这个问题的答案,但在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;
}
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 从持续时间构造std::chrono::system_clock::time_point
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 使用简单类型列表实现的指数编译时间.为什么
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在已经使用Git的情况下减少编译时间
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 从文本文件中读取时钟时间和事件时间并进行处理
- 具有未知值时的时间复杂性
- 如何减少花费的时间
- C++在变量给定的指定时间内关闭电脑
- rcpp函数中的清理时间很长
- C++:floor unix时间戳到UTC月份
- 如何在c++中录制具有精确帧时间戳的视频
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- KMP算法和LPS表构造的运行时间
- 为什么std::互斥需要很长的、非常不规则的时间来共享
- 使用Boost Interprocess创建托管共享内存需要很长时间