How to assign a random number using a cryptographically secure random number generator in C++

3 Answers

0 votes
#include <iostream>
#include <random>

int main() {
    std::random_device rd; 
    std::mt19937 generator(rd()); 
    std::uniform_int_distribution<int> distribution(1, 100); // 1 to 100

    int random_number = distribution(generator);
    std::cout << "Random number: " << random_number << std::endl;
}



/*
run:

Random number: 42

*/

 



answered Aug 20, 2025 by avibootz
0 votes
#include <iostream>
#include <random>

int main() {
    std::random_device rd; 
    
    int random_number = rd() % 100 + 1; // 1 to 100
    
    std::cout << "Random number: " << random_number << std::endl;
}



/*
run:

Random number: 37

*/

 



answered Aug 20, 2025 by avibootz
0 votes
#include <iostream>
#include <fstream>

int main() {
    //  OS-specific APIs - /dev/urandom on Linux
    std::ifstream urandom("/dev/urandom", std::ios::in | std::ios::binary);
    if (!urandom) {
        std::cerr << "Failed to open /dev/urandom" << std::endl;
        return 1;
    }

    unsigned int random_number;
    urandom.read(reinterpret_cast<char*>(&random_number), sizeof(random_number));
    urandom.close();

    random_number = random_number % 100 + 1; // 1 to 100
    std::cout << "Random number: " << random_number << std::endl;
}



/*
run:

Random number: 72

*/

 



answered Aug 20, 2025 by avibootz
...