Help with Delay

Hello I need help with my delayed program.

I want to add delay of 3 seconds and its not working.

I am using DEV C++ compiler

Look at this code and please tell me what's wrong
(its saying Sleep was not decalred in this scope)
I am trying to make a program that will shoot every time I press a random key on the keyboard and if I will press the "R" key it will say reloading magazine and after 3 - 5 seconds it will react again



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
#include <iostream>
#include <conio.h>
#include <time.h>
using namespace std;



int main() { 
	char key;
	int Value;
	
	cout << "Press a key" << endl;
	
	while(1) { 
	key=getch();
	Value=key;
		if(Value == 27) {
			break;
		}
		if(Value == 144){
			cout << "Reloading Magazine" << endl;
			sleep(3)
			cout << "Press a key to shoot" << endl;
		}
		cout << "Fire" << endl;
	}
}


thanks for the helpers
Last edited on
If you're using Windows then you can use WinApi's Sleep function (Sleep and not sleep, it's case sensitive) so for that you must include #include <Windows.h>

Otherwise you will have to rely on some dependency like chrono for a cross-platform way to pause the program, which you should probably do instead.

edit: I don't know why I said dependency.. chrono is part of the standard library..
Last edited on
Thanks for the help :D
Hello OshriMakk,

Since "Sleep()" is a Windows function that not everyone can use I use this most often:

std::this_thread::sleep_for(std::chrono::seconds(3)); // <--- Needs header files chrono" and "thread".
And you can change "seconds" to "milliseconds" for those in between times. Just remember that 1 second = 100 milliseconds. This should work better for anything that is not Windows based.

Hope that helps,

Andy
Thanks Andy for the help :D
it helped me alot.



NICE DAY :D
Last edited on
sleep stops the program (or more precisely, the current thread, which may be the only thread you have). if you want to be able to do other stuff, just not shoot, you need to just check the time until 3 sec have passed in your game loop ... looks like this in pseudo code

if reload
now = getcurrenttime

if shoot && getcurrenttime >= now+offset
allow shoot
else
deny shoot

which I would have to look up how to do in chrono, I haven't done a lot of timing with the newer tools.
Last edited on
K thanks, :D
Topic archived. No new replies allowed.