About the C++ timer

closed account (L3ApX9L8)
So am trying to write a program that 'allows' the user to enter data for x-seconds, stopping the timer if this happens, and doing something else if this is not the case...

The only problem is, im pretty confused about the timer in c++
anyone could explain things up a bit, please?
There is no timer in C or C++. The OS supplies one, though.

If you are on Windows:
1
2
3
4
5
6
7
8
9
#include <windows.h>

bool iskeypressed( unsigned long timeout = 0 /* milliseconds */ )
  {
  return WaitForSingleObject(
    GetStdHandle( STD_INPUT_HANDLE ),
    0
    ) == WAIT_OBJECT_0;
  }
http://www.google.com/search?btnI=1&q=msdn+WaitForSingleObject

If you are on POSIX (Unix/Linux/Mac OS X/etc)
1
2
3
4
5
6
7
8
9
10
#include <unistd.h>
#include <poll.h>

bool iskeypressed( unsigned long timeout = 0 /* milliseconds */ )
  {
  struct pollfd pls[ 1 ];
  pls[ 0 ].fd = STDIN_FILENO;
  pls[ 0 ].events = POLLIN | POLLPRI;
  return poll( pls, 1, (int)timeout ) > 0;
  }
http://linux.die.net/man/2/poll
If you are on some ancient system that does not supply poll(), let me know and I'll give you a version that uses select().

Use the function to check for keypresses. If it returns true, then you know you have input to read. Otherwise your timeout has expired.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.