### random number generator not working properly

I'm trying to generate random social security numbers from 000 - 00 - 0000 to 999 - 99 - 9999 , so what I did was generate a random number from 0 to 999999999, convert the int to a string, and then add leading zero if it wasn't a 9 digit number, and then added a '-'. However, after I set the width to 9 and added the leading zeros, my program will not generate anything in the first four digits.

 ``123456789101112131415161718192021222324252627`` ``````#include #include #include #include using namespace std; int rng11(){return 1+(rand()%999999999);} int main() { srand(time(NULL)); string student[100]; for (int i=0; i<100; i++) { int z = rng11(); string result; stringstream convert; convert << std::setw(9) << setfill('0') << z ; result = convert.str(); result.insert(3,1, '-'); result.insert(6,1, '-'); student[i] = result; cout << student[i] << endl; } return 0; }``````
Last edited on
rand() generates a random number between zero and RAND_MAX.

RAND_MAX could be as low as 32767.

If you never see a number above 000099999 , it suggests your RAND_MAX is less than 100000.

rand() is bad. Don't use rand().
https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

Here is a better, C++11 random number generator: https://www.guyrutenberg.com/2014/05/03/c-mt19937-example/

Don't use modulus to trim your random numbers to a range you want. That makes them much, much less random.

Try something like:
`mt19937::result_type seed = time(0);`
and then to get your numbers:
 ``12`` ``````auto dice_rand = std::bind(std::uniform_int_distribution(0,999999999), mt19937(seed));``````
Last edited on
Topic archived. No new replies allowed.