Making a StopWatch

Pages: 12
andywestken wrote:
Adding an 0x1 == test to the shift version, to shut up the warning,
stops it from working for some reason (have not looked into this yet).

It stops working because, if the key is pressed, the result of GetAsyncKeyState
right shifted by 15 bits is 1111111111111111 instead of 0000000000000001.

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 <iostream>
#include <string>
#include <bitset>

using namespace std;

inline string short_to_bits(short n)
{
    return bitset<16>(n).to_string();
}

inline short bits_to_short(const string & str)
{
    return bitset<16>(str).to_ulong();
}

int main()
{
    short n = bits_to_short("1000000000000000");

    cout << short_to_bits(n >>= 15) << endl;

    cout << ((short)0x1    == n) << endl;
    cout << ((short)0xffff == n) << endl;
}
Last edited on
The Windows API provides a very convenient wait function to help you out.
http://www.cplusplus.com/forum/beginner/5619/#msg25047

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iomanip>
#include <iostream>
#include <windows.h>
using namespace std;

bool iskeypressed( unsigned timeout_ms = 0 )
  {
  return WaitForSingleObject(
    GetStdHandle( STD_INPUT_HANDLE ),
    timeout_ms
    ) == WAIT_OBJECT_0;
  }

int main()
  {
  cout << "Press ENTER to start the stopwatch.";
  iskeypressed( INFINITE );
  cin.ignore( 1000, '\n' );
  cout << "Press ENTER to stop the stopwatch.\n00:00";

  unsigned qsec = 0;
  unsigned min  = 0;

  cout << setfill( '0' );

  while (!iskeypressed( 250 ))
    {
    qsec += 1;
    if ((qsec / 4) >= 60)
      {
      qsec = 0;
      min += 1;
      }
    if ((qsec % 4) == 0)
      {
      cout << "\r" << setw( 2 ) << min << ":" << setw( 2 ) << (qsec / 4);
      }
    }

  cin.ignore( 1000, '\n' );
  return 0;  
  }
@m4ster r0shi

OK - but I still find my version rather clearer. To shut up the warning in the shift version I find I need to use either

1
2
3
4
inline bool IsPressed(int vkey) 
{
    return 0xFFFFFFFF == (GetAsyncKeyState(vkey) >> 15);
}


or

1
2
3
4
inline bool IsPressed(int vkey)
{
    return 0x1 == ((USHORT)GetAsyncKeyState(vkey) >> 15);
}


or with const

1
2
3
4
5
inline bool IsPressed(int vkey)
{
    const USHORT topBit = 0x8000;
    return topBit == ((USHORT)GetAsyncKeyState(vkey) >> 15);
}

Last edited on
Suit yourself. I like warnings :D
So you don't work (have never worked) with a zero-warning policy in place??
Nope.
Topic archived. No new replies allowed.
Pages: 12