I wrote a program that create a string array which contains random strings, and the rand_str()
is to make a string of 20 length long. When I use sleep()
, the result is exactly what I want. However, I think sleep()
shouldn't appear in my code. Removing sleep()
, the random strings created are totally different. I am really confused about this. Could someone help to explain why this happens?
#include <iostream>
#include <string.h>
#include <random>
#include <ctime>
#include <cstdlib>
#include <windows.h>
#include <stdlib.h>
#include <array>
#define show(w) for(auto val:w){cout<<val<< " ";}cout<<endl;
using namespace std;
char *rand_str(char *str,const int len);
int main(){
const int len = 10;
char *a[len];
string c[len];
array<string,len> ar;char b[len][21];
for (int i = 0; i < len; ++i) {
ar[i] = rand_str(b[i], 21);
fflush(stdin);
// Sleep(1000);
}
show(ar);
return 0;
}
char *rand_str(char *str,const int len){
srand(time(NULL));
int i;
for(i=0;i<len;++i)
{
switch((rand()%3))
{
case 1:
str[i]='A'+rand()%26;
break;
case 2:
str[i]='a'+rand()%26;
break;
default:
str[i]='0'+rand()%10;
break;
}
}
str[len - 1]='\0';
return str;
}
Not using sleep() :
Using sleep() :