rng works on mac, but not windows?

I made a class that generates random SSID. and this is part of the function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int Student::generateTokenType()
{
    std::random_device m_mt;
    std::uniform_int_distribution<int> dist(0, 999999999);
    return dist(m_mt);
}


string Student::set_ssid()
{
  
    int randomNumber = generateTokenType();
    string result;
    stringstream convert;
    convert  << setw(9) << setfill('0') << randomNumber;
    result = convert.str();
    result.insert(3,1,'-');
    result.insert(6,1,'-');
    ssid = result;
    return ssid;
}


How do I fix this? On mac it will properly generate random numbers, but on windows it will generate the same number over and over.
Last edited on
Sounds like it needs srand().
@kbw

Where would I put the srand()?

@kbw,
why would he need to use srand for C++11 random functionality ?
Normally srand is used with rand
> On mac it will properly generate random numbers,
> but on windows it will generate the same number over and over.

std::random_device of the GNU library on windows is a pseudo-random number engine which would generate the same sequence over and over again.

Either use the Microsoft Library, or if the GNU library must be used on Windows, pick a pseudo-random number engine and seed it with a reasonable random seed.

For example:
1
2
3
4
5
6
7
8
9
10
#include <random>
#include <ctime>

int generateTokenType()
{
    static std::mt19937 m_mt( std::time(nullptr) );
    static std::uniform_int_distribution<int> dist( 0, 999999999 );

    return dist(m_mt);
}
pick a pseudo-random number engine and seed it with a reasonable random seed

This is generally a good advice, unless you need the non-deterministic nature of random_device, because random_device is often orders of magnitude slower.
Topic archived. No new replies allowed.