User Activated Stop

I was wondering if someone could help me with this:

I have a countdown that uses Sleep(); for the pause and Do-While for the loop.
I was thinking that somewhere in the middle of the code, maybe in the do{ } part of it, before it loops, it could ask for a user to hit a key to stop the program.
But if they don't before the next number appears, it stops asking for the user input until it passes by the cin function again and repeats the process until either:

A) The user hits a key
B) The countdown reaches 0 (zero).

I have the countdown code:

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
// Do-While Practice with Sleep

// Set-Up
#include <iostream>
#include <cstdlib>
#include <windows.h>
using namespace std;

// Main
int main()
{
	cout << "Do-While Practice :D" << endl;
	
	int a = 100;
	
	do
	{
		Sleep(500);
		cout << a << endl;
		a--;
	} while (a != -1);
	
	system("PAUSE");
	return 0;
}


...But do not know how to or if I can deploy my idea. I use system("PAUSE") because to an inexperienced Windows user, it would seem that the program stopped working.
I think what you whant is GetAsyncKeyState(VK_...)
use like this:
1
2
3
4
5
6
7
8
//...
do
{
     if (GetAsyncKeyState(VK_ESCAPE)) break;
     Sleep(500);
     cout << a << endl;
     a--;
} while (a != -1);

so if the user presses escape, the program will end.


( Something similar could be achieved by getch() from conio.h )
Last edited on
I was wondering if it was possible to make it let you press any key to exit?
Last edited on
Well, then just check for the key, then return 0 (or something similar) to quit the program.
have you tried getch()?
That should return a value only if a key was pressed
Topic archived. No new replies allowed.