Random value in C++

I was practicing some C++, I created that simple dice game exercise, so I ran into a problem, How can I generate random values in C and C++?

Taking a look at the site (C plus plus ) I found an example using time as seed (seed), the problem is after that, I created a code as an example, in it I am creating a class "given" and creating two methods, the Seed and the "roll", one will create the seed and generate one value and the other will pass the fixed values and call the Seed, inside the main I instantiated 3 objects of type Dado and did the "scroll", always fall the same values for the 3 objects, are different instances, as in other languages, should not generate different values? This is the goal, create different values for each data created, follow the codes:

Given.h

#ifndef DADO_H
#define DADO_H

#include <cstdlib>
#include <ctime>

class Dado
{
public:
    int Seed(int max, int min);
    int Rolar();
};

#endif

Given.cpp

#include "dado.h"

int Dado::Seed(int max, int min){
   srand(time(NULL));
    return rand() % max + min;
}

int Dado::Rolar(){
    int val_max = 6;
    int val_min = 1;
    return Seed(val_max, val_min);
}

Main.cpp

#include <iostream>
#include "dado.h"

using namespace std;

int main()
{
    Dado seed;
    Dado dado_1;
    Dado dado_2;

    cout << "Seed:   " << seed.Seed(6,1) << "\n";
    cout << "Dado_1: " << dado_1.Rolar() << "\n";
    cout << "Dado_2: " << dado_2.Rolar() << "\n";

    return 0;
}

Makefile for help anyone who wants to test

all: main
    rm *.o && ./teste

main: main.o dado.o
    g++ -g -o teste main.o dado.o -Wall

main.o: main.cpp dado.h
    g++ -c -g main.cpp -Wall

dado.o: dado.cpp dado.h
    g++ -c -g dado.cpp -Wall

I also created a demo in ideone with some changes, nothing that changes the result, just to organize the visualization (I do not use this tool much, so I do not know if it works with more than one file to make the cpp and header).

 3
Author: Maniero, 2017-03-12

1 answers

The problem is that you are thinking you should create a new seed each time when in fact you should create the seed only once.

Still has two things that this code is not ideal. The random generation of the C that was used is not very suitable, it is better to use that of the C++. And this class is no use at all, the most it could do would be to encapsulate the generation into a simple function. Creating a class for this is killing little bird with a cannon. So I did more simple as possible. But remember the seed can only be generated once.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(NULL));
    cout << "Dado_1: " << rand() % 6 + 1 << "\n";
    cout << "Dado_2: " << rand() % 6 + 1 << "\n";
}

See working on ideone. E no repl.it. also I put on GitHub for future reference .

 4
Author: Maniero, 2020-05-06 18:54:05