forked from eceuwaterloo/ece650-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusing_rand.cpp
More file actions
35 lines (29 loc) · 1.02 KB
/
using_rand.cpp
File metadata and controls
35 lines (29 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// an example of reading random numbers from /dev/urandom
// https://stackoverflow.com/questions/35726331/c-extracting-random-numbers-from-dev-urandom
#include <iostream>
#include <fstream>
int main(void) {
// open /dev/urandom to read
std::ifstream urandom("/dev/urandom");
// check that it did not fail
if (urandom.fail()) {
std::cerr << "Error: cannot open /dev/urandom\n";
return 1;
}
// read a random 8-bit value.
// Have to use read() method for low-level reading
char ch = 'a';
urandom.read(&ch, 1);
// cast to integer to see the numeric value of the character
std::cout << "Random character: " << (unsigned int)ch << "\n";
// read another 8-bit value
urandom.read(&ch, 1);
std::cout << "Random character: " << (unsigned int)ch << "\n";
// read a random unsigned int
unsigned int num = 42;
urandom.read((char*)&num, sizeof(int));
std::cout << "Random character: " << num << "\n";
// close random stream
urandom.close();
return 0;
}