'Rand() statement always giving the same number

so im trying to make a random number generator that will give me 1, 2 or 3 but for some reason it always give me 3. sorry its in french but i figured it didnt really matter. also tell me if something is missing its my first time posting here.

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

RPC choixOrdi()
{
    int min = 1;
    int max = 3;
    int randNum = rand() % (max - min + 1) + min;
    return convertirRandNum(randNum);
    
}

RPC convertirRandNum(int randNum)
{
    switch (randNum)
    {
    case 1:
        return RPC::Roche;
        break;
    case 2:
        return RPC::Papier;
        break;
    case 3:
        return RPC::Ciseaux;
        break;
    default:
        return RPC::Invalid;
    }
}```


Solution 1:[1]

The problem is that the random is not properly seeded. As current computer cannot generate a true random number, it generates the deterministic pseudo-random number sequence, which has to be initialized by number you choice. It is called seeding. One solution is that you seed the rand() by current time using srand(time(NULL)). such as:

RPC choixOrdi()
{
    int min = 1;
    int max = 3;
    srand(time(NULL));
    int randNum = rand() % (max - min + 1) + min;
    return convertirRandNum(randNum);
    
}

There can be more improvement. You can just throw away the C-style random generator, and use std::random_device, std::mt19937 and so on. You can find examples here: https://en.cppreference.com/w/cpp/numeric/random

EDIT: As someone else pointed out, seeding rand(time(NULL)) each time when the function is called is really a bad choice, especially when you have multiple clients calls the function simultaneously. If random_device is available to you, this can be other workaround:

RPC choixOrdi()
{
    int min = 1;
    int max = 3;
    static std::random_device rd;
    static std::uniform_int_distribution<int> dist(min, max);
    return convertirRandNum(dist(rd));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1