notaorb
notaorb

Reputation: 2190

C++: random number generation using Stroustrup example?

I'm using the random number generation from Stroustrup C++ 4th Ed. Page 129. Unfortunately, it does not appear to be random and keeps generating and int 1. Does anyone know why it's not generating a random number 1-6?

#include <random>
#include <iostream>
#include <functional>
using namespace std;

int main(int argc, char *argv[])
{
    using my_engine = default_random_engine;
    using my_distribution = uniform_int_distribution<>;

    my_engine re {};
    my_distribution one_to_six {1,6};
    auto die = bind(one_to_six,re);

    int x = die();

    cout << x << endl;

    return 0;
}


g++ -pedantic -lpthread test92.cc && ./a.out
1

Upvotes: 1

Views: 74

Answers (1)

Coral Kashri
Coral Kashri

Reputation: 3506

You have to seed your engine (re) with some random:
Replace:

my_engine re {};

With:

std::random_device rd;  //Will be used to obtain a seed for the random number engine
my_engine re(rd());

Upvotes: 1

Related Questions