-
February 23rd, 2004, 05:15 AM
#1
Random numbers
hi!
I am using the following code to generate a random string. But each time i get the same string output. Can anyone help.
char myarray[22];
char* CGeneratorApp::GenerateString()
{
myarray[21]='\0';
for(int k=0;k<21;k++)
{
myarray[k] = (char)(((int)rand()%25)+65);
}
char first[2];
intUsed++;
sprintf(first,"%d",intUsed);
if(intUsed<10)
{
first[1]=first[0];
first[0]='0';
}
first[0]=(char)((int)first[0]+27);
first[1]=(char)((int)first[1]+27);
myarray[8]=first[0];
myarray[10]=first[1];
AfxMessageBox(myarray);
return myarray;
}
Thnx in advance
-
February 23rd, 2004, 05:43 AM
#2
You need to initialize the random seed using srand() before calling rand(). e.g. srand(clock());
-
February 23rd, 2004, 12:00 PM
#3
Here is a related post which offers additional, useful information.
Sincerely, Chris.
http://www.codeguru.com/forum/showth...hreadid=281630
You're gonna go blind staring into that box all day.
-
February 23rd, 2004, 11:25 PM
#4
Thnx Everybody
Thnx Everybody,
U were of quite good help.
-
February 26th, 2004, 06:34 AM
#5
Originally posted by Kheun
You need to initialize the random seed using srand() before calling rand(). e.g. srand(clock());
Indeed, you need to call srand(), but not using clock(), because clock() will (possibly) return the same number, so the random seed will be initialized in the same way. A better way is to call srand like this:
Code:
srand( (unsigned)time( NULL ) );
-
February 26th, 2004, 07:20 AM
#6
Indeed,
Some developers even seed rand using some sort of a high-frequency ticker in the system, for example the time-stamp-counter in Pentium systems.
I think that this is described in some other posts such as the link in my other response above.
Sincerely, Chris.
You're gonna go blind staring into that box all day.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|