Home > OS >  Random ABCD char generator
Random ABCD char generator

Time:05-26

I am making a quiz game and want when the player calls his friend(which is a simple cout), the program prints a random char of an answe(A, B, C or D) and a random number to present how sure he is(from 1 to 100). Whetever I try the char in console is always D, and the number is always 87. I don't know how to make this work. This is the current code:

char x = *("ABCD"   rand() % 4);
int y = 1  (rand() % 100);

CodePudding user response:

Random numbers generation is not as simple as you might think.
See here some general info: Random number generation - Wikipedia.

In order to use rand properly, you should initialize the random seed (see the link). Using the current time as seed is recommended for getting "nice" random values.

Below you can see a fixed version for your code, that produce different values (potentially) in each run:

#include <time.h>
#include <stdlib.h>
#include <iostream>

int main() {
    srand(static_cast<unsigned int>(time(0)));
    char x = *("ABCD"   rand() % 4);
    int y = 1   (rand() % 100);
    std::cout << x << "," << y << std::endl;
    return 0;
}

However - since C 11 the standard library has good and modern support for random generators. See: Pseudo-random number generation.
It requires a bit more boilerplate, but you have better control over the generation of random values. See more info in the <random> header, which contains a lot of classes and utilities.

A good alternative to rand() in your case is the std::uniform_int_distribution.
Here is some info why to prefer it over the old rand(): What are the advantages of using uniform_int_distribution vs a modulus operation?.

The code below shows how to use it in your case:

#include <random>
#include <iostream>

int main() {
    std::random_device rd;  // Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> distrib1(0, 3);   // For getting a random integer in the range 0..3
    std::uniform_int_distribution<> distrib2(1, 100); // For getting a random integer in the range 1..100

    char ABCD[] = "ABCD";
    std::cout << ABCD[distrib1(gen)] << ',' << distrib2(gen) << std::endl;
    return 0;
}
  • Related