c_kusanagi
c_kusanagi

Reputation: 41

Why can't I use rand() with the size of an array?

I am trying to generate a number between 0 and the size of an array. There is my code but the output is always 2. Edit: I tried with another compiler and the output was only 7 Please help me.

There is my full code

#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <string>
#include <ctime>

using namespace std;
int main (){

    string motMystere = ("Bonjour");
    int tailleMotMystere (0);
    vector<string> motMelange;
    tailleMotMystere= motMystere.size();
    srand(time(0));
    int nombreRandom = 0;
    
    nombreRandom = rand() % tailleMotMystere;
    cout << motMystere.size() << endl;
    return 0;
}

Upvotes: 0

Views: 403

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117408

You will get a new random number every new second you run the program (since you use time() to seed the pseudo random number generator), but you are not printing the random number, you are printing the length of motMystere, so change

from

cout << motMystere.size() << endl;

to

cout << nombreRandom << endl;

Note that using srand() and rand() is discouraged since C++11. Use the new <random> classes and functions.

Example:

#include <cstddef>
#include <iostream>
#include <random>
#include <string>

int main (){
    std::mt19937 prng(std::random_device{}()); // A seeded PRNG

    std::string motMystere  = "Bonjour";
    size_t tailleMotMystere = motMystere.size();
    
    // Distribution: [0, tailleMotMystere)
    std::uniform_int_distribution<size_t> dist(0, tailleMotMystere - 1);
    
    size_t nombreRandom = dist(prng);
    std::cout << nombreRandom << '\n';
}

Upvotes: 2

john
john

Reputation: 87957

The error is that you are calling srand every time before you call rand()

srand(time(0));
int nombreRandom = 0;

nombreRandom = rand() % tailleMotMystere;

Instead you should call srand once at the beginning of your program.

Upvotes: 1

Related Questions