Reputation: 3
I am making a timer to calculate the number of seconds until the user presses 3 however the program doesn't work, and no value is saved in the integer variable 'sec'. where am i wrong? I have include windows.h and ctime.h Here's the code:
void func(){
int sec=0
cout<<"Press 3 to end Timer";
cin>>t;
while(t!=3){
Sleep(1);
sec++;}
if(t==3)
{
cout<<"Timer ended";
}
}
Upvotes: 0
Views: 40
Reputation: 9078
This is because cin >> t is blocking. That is, execution doesn't move to your while-loop until the input is complete.
Something like this would work:
#include <chrono>
// This is just to make the example cleaner.
using namespace chrono;
...
system_clock::time_point startTime = system_clock::now();
cin >> t;
system_clock::time_point endTime = system_clock::now();
milliseconds duration = time_point_cast<milliseconds>(endTime - startTime);
At this point, duration.count() is the number of milliseconds spent waiting for input. You can do some math to turn it into seconds, or you could use seconds instead like this:
seconds duration = time_point_cast<seconds>(endTime - startTime);
but in this case, 2.9 seconds will show up as 2 seconds (I think). So I'd do this to output it:
cout << "Duration: " << (double)duration.count() / 1000.0 << endl;
Or something along those lines. I'm typing this raw, so there might be typos.
Upvotes: 2