-1

i have been trying to make program that prints random string out of string array. But it is throwing nothing.

I have chaged random number generator algorythm, but it printed same string every time. So i made test aplication and it doesnt work anymore. Here is my code:

#include <iostream>
using namespace std;

int randomNumber(int min, int max) {
    int x = min + rand() % max;
    return x;
}

int main() {
    string lmao[] = {"xd", "hahaha",",","fjdskl", "fjdskl", "fjkdsljfkdsl","uuruur","fjdksl"};
    string lastZ = "";
    for (int i = 0; i <= 10; i++) {
        int x = sizeof(lmao) / sizeof(int);
        int y = randomNumber(0, x);
        string z = lmao[y];
        if (z == lastZ) {
            cout << "Fail";
        }
        else {
            lastZ = z;
            cout << "Succes";
        }
    }
    return 0;
}
  • 1
    _"...If `rand()` is used before any calls to `srand()`, `rand()` behaves as if it was seeded with `srand(1)`..."_ see [`rand`](https://en.cppreference.com/w/c/numeric/random/rand) – Richard Critten Nov 30 '22 at 17:03
  • Dupe of: https://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-an-entire-range, https://en.cppreference.com/w/cpp/container/vector, https://stackoverflow.com/questions/9459035/why-does-rand-yield-the-same-sequence-of-numbers-on-every-run. Also I have no clue what `int x = sizeof(lmao) / sizeof(int);` is supposed to do – pptaszni Nov 30 '22 at 17:05
  • @pptaszni `sizeof()` method returns size of array but in bytes, so according to tutorial on w3schools is this supposed to convert it to regular number – avixis12 Nov 30 '22 at 17:12

1 Answers1

0
  1. Don't use rand, use the <random> header.
  2. If you must use rand, seed it with srand before hand.
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • If you must use the `` header, seed your generator before hand. Switching to the new generators doesn't remove this issue. – Pete Becker Nov 30 '22 at 17:50