-5

I am trying to display "first", "among", "shift", "debug", and "craft" randomly, but it prints "shift" every time I run the project. In case this has anything to do with my problem, I'm using Xcode on macOS Ventura.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    vector <string> vec {"first", "among", "shift", "debug", "craft"};
    int rand_num = rand() % vec.size();
    string word;
    word = vec[rand_num];
    
    cout << word;
    
    return 0;
}

I expected it to display "first", "among", "shift", "debug", or "craft" randomly, but it only printed "shift"

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 5
    Did you try seeding the random number generator? – possum Dec 30 '22 at 18:06
  • 2
    Every C or C++ textbook that explains `rand` also explains another function too, and provides detailed instructions for how to use it correctly. What does your textbook say? – Sam Varshavchik Dec 30 '22 at 18:08
  • You might be interested in [this](https://en.cppreference.com/w/cpp/algorithm/random_shuffle) if you're actually trying to learn c++. – πάντα ῥεῖ Dec 30 '22 at 18:24
  • 3
    Does this answer your question? [How to generate a random number in C++?](https://stackoverflow.com/questions/13445688/how-to-generate-a-random-number-in-c) – rturrado Dec 30 '22 at 18:27

2 Answers2

3

The rand() function gives a random value between 0 and RAND_MAX which will be same every time you run the program unless you seed it using the srand() function. Your code does not use srand() so rand_num is initialized with the same value every time you run the program.

user4581301
  • 33,082
  • 7
  • 33
  • 54
Abyss
  • 31
  • 4
2

rand() generates a pseudo-random sequence of numbers that will be the same given the same seed. Since you aren't explicitly initializing the seed using srand, you keep getting the same random value.

One way of initializing it so it gets a different seed in each execution is to use the current time:

// Must be called before you call rand:
srand (time(NULL));
Mureinik
  • 297,002
  • 52
  • 306
  • 350