Random "rand()" and srand(time(NULL))

Hi guys; sorta got a question and a comment, but more of a question:

So first of all this is my source code(Heads up, it was written for opening the cd drive and isn't all my 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
26
27
#include <iostream>
#include <string>
#include <time.h>
#include "windows.h"
#include "winioctl.h"
using std::string;
using namespace std;

int main(int argc, char* argv[])
{
 // FreeConsole(); will make the console not show
 //FreeConsole();

 srand (time(NULL));
 cout << (rand() % 100 + 1) << " is the number...";

 // Replace 'd' by the drive letter of the CD-ROM
 string sdrive("\\\\.\\d:");
 HANDLE hcd=CreateFile(sdrive.c_str(),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_READONLY,NULL);
 DWORD d=0;
 DeviceIoControl(hcd, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &d, NULL);
 CloseHandle(hcd);
 string exit;
 cout << "\nPress \"Enter\" to exit...";
 getline(cin, exit);
 return 0;
}


What I was trying to figure out was that when I ran my program, random numbers work, but only sometimes(Anyway, what I was doing wrong was not allowing any time between my running the program over and over). but after about an hour of investigation, I found out that the numbers go up by about 1 for every 1 second that passes... That obviously has to do with the srand(time(NULL))

Main question: What does srand(time(NULL)) do, and why is it needed for a random number??
Thx,
Filetestingman
It seeds the pseudo random number generator that rand() uses
http://www.cplusplus.com/reference/clibrary/cstdlib/srand/
Ok... so I rewrite the NULL as a number(I.e., 1000 would be one second?) or what??? I'm too new for doing this stuff :)
Last edited on
maybe this can work :
1
2
srand((unsigned)time(NULL));//time should write like this .
cout<<(rand()%100+1);<<"this is the number :"<<"\n";
You can replace time(NULL) with any interger eg: srand(1234);
( if you seed the PRNG with a fixed value, you'll get every time the same sequence )
NULL is a time_t pointer http://www.cplusplus.com/reference/clibrary/ctime/time/ http://www.cplusplus.com/reference/clibrary/ctime/time_t/
Last edited on
Topic archived. No new replies allowed.