A Pause Function Dealing with Floating Point?

Hi everyone!

I'm writting a simple program which prints something at a fixed interval of time. Say, “|” every second for 10 seconds. The way I figured doing it is to write a function that pauses for a fixed amount of time. And the printing part is in a for loop in main().

It works fine except for any non-integer intervals because of the limitations of time_t. A simplified excerpt of the code is included.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <ctime>
void pause(double waitTime) {
   time_t start = time(0);
   while(difftime(time(0), start) < waitTime);
}

int main() {
   double interval;
   cin >> interval;

   for(int i; i < 10; i++) {
      cout << "|";
      pause(interval);
   }

   return 0;
}


Can anyone please help me improve this code so that the function can work on floating points too? I realize that this might have to be machine dependent but a simple code will be much appreciated.

Thanks!!
cin is undefined. I assume you meant the standard in. You forgot to #include <iostream>
Also, please do put the open bracket beneath the functions and for loops, it (imo) makes it much more readable as it makes it more obvious where the block starts.
Here's your new code.

Mind you, it's very tedious to use double. Use milliseconds instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <ctime>
#include <iostream>

void pause(unsigned int milliseconds)
{
	time_t final= milliseconds + clock();
	while(milliseconds < final)
	{
		milliseconds= clock();
	}
}

int main()
{
   unsigned int interval;
   std::cout<<"enter milliseconds per interval";
   std::cin >> interval;

   for(int i=0; i < 10; i++)
   {
      std::cout << "|";
      pause(interval);
   }
   return 0;
}
Thank you Nexius! It worked great. I'll post more questions if I stumble upon any others.
Topic archived. No new replies allowed.