我有一个控制台应用程序,旨在仅在Windows上运行。它是用 C ++ 编写的。有什么方法可以等待 60秒(并在屏幕上显示剩余时间)然后继续执行代码流?
我尝试了与互联网不同的解决方案,但没有一个起作用。它们要么不起作用,要么它们无法正确显示时间。
答案 0 :(得分:0)
您可以使用sleep()系统调用来睡眠60秒。
您可以点击此链接,了解如何使用系统调用Timer in C++ using system calls设置60秒计时器。
答案 1 :(得分:0)
可能将Waitable Timer Objects的Perion设置为1秒以完成此任务。可能的实施方式
VOID CALLBACK TimerAPCProc(
__in_opt LPVOID /*lpArgToCompletionRoutine*/,
__in DWORD /*dwTimerLowValue*/,
__in DWORD /*dwTimerHighValue*/
)
{
}
void CountDown(ULONG Seconds, COORD dwCursorPosition)
{
if (HANDLE hTimer = CreateWaitableTimer(0, 0, 0))
{
static LARGE_INTEGER DueTime = { (ULONG)-1, -1};//just now
ULONGLONG _t = GetTickCount64() + Seconds*1000, t;
if (SetWaitableTimer(hTimer, &DueTime, 1000, TimerAPCProc, 0, FALSE))
{
HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
do
{
SleepEx(INFINITE, TRUE);
t = GetTickCount64();
if (t >= _t)
{
break;
}
if (SetConsoleCursorPosition(hConsoleOutput, dwCursorPosition))
{
WCHAR sz[8];
WriteConsoleW(hConsoleOutput,
sz, swprintf(sz, L"%02u..", (ULONG)((_t - t)/1000)), 0, 0);
}
} while (TRUE);
}
CloseHandle(hTimer);
}
}
COORD dwCursorPosition = { };
CountDown(60, dwCursorPosition);
答案 2 :(得分:0)
请注意,这是Windows特定的代码
//counter is the amount of seconds
int counter = 60;
_sleep(1000);
while (counter >= 1)
{
cout << "\rTime remaining: " << setw(5) << counter << flush;
_sleep(1000);
counter--;
}
答案 3 :(得分:0)
在c ++中,您可以使用倒数计时。请按照以下逻辑操作,以便您在屏幕上显示剩余时间。
for(int min=m;min>0;min--) //here m is the total minits as per ur requirements
{
for(int sec=59;sec>=;sec--)
{
sleep(1); // here you can assign any value in sleep according to your requirements.
cout<<"\r"<<min<<"\t"<<sec;
}
}
如果您需要更多帮助,请按照link here
希望它会起作用,请告诉我它是否在您的情况下起作用?或者您需要任何帮助。
谢谢!
答案 4 :(得分:0)
这可能会有所帮助,尚不清楚问题是什么,但这是一个从10秒开始的倒数计时器,您可以更改秒数并添加分钟和小时。
#include <iomanip>
#include <iostream>
using namespace std;
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
int main()
{
for (int sec = 10; sec < 11; sec--)
{
cout << setw(2) << sec;
cout.flush();
sleep(1);
cout << '\r';
if (sec == 0)
{
cout << "boom" << endl;
}
if (sec <1)
break;
}
}