Reputation: 183
I have a console application that is intended to only run on windows. It is written in C++. Is there any way to wait 60 seconds (and show remaining time on screen) and then continue code flow?
I've tried different solutions from the internet, but none of them worked. Either they don't work, or they don't display the time correctly.
Upvotes: 1
Views: 42027
Reputation: 1
this might be of some help, it's not entirely clear what the question is but this is a countdown timer from 10 seconds, you can change the seconds and add minutes as well as hours.
#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;
}
}
Upvotes: 0
Reputation: 183
//Please note that this is Windows specific code
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
int counter = 60; //amount of seconds
Sleep(1000);
while (counter >= 1)
{
cout << "\rTime remaining: " << counter << flush;
Sleep(1000);
counter--;
}
}
Upvotes: 3
Reputation: 1351
In c++ you can use countdown. please go through with the following logic which will allow you to show remaining time on the screen.
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;
}
}
if you need more help on this then please follow the link here
Hope it will work, please let me know that it is working in your case or not? or if you need any help.
Thanks!
Upvotes: -2
Reputation: 33706
possible use Waitable Timer Objects with perion set to 1 second for this task. possible implementation
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);
Upvotes: 0
Reputation: 696
You can use sleep() system call to sleep for 60 seconds.
You can follow this link for how to set 60 seconds timer using system call Timer in C++ using system calls.
Upvotes: 0