Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,912 questions

51,844 answers

573 users

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
...