6

I would like to be able to save the state of a random number generator in a .txt file and read it back in. I have heard that with c++11, this can be done using the << and >> operators. However, I'm not sure how exactly I would do this. I have a random number generator initialized as follows:

mt19937 myRandomGenerator(1);
normal_distribution<double> myDistribution(0.0, 1.0);

I would like to be able to save the state of myRandomGenerator in the file save.txt. How would I do thi?

covertbob
  • 691
  • 2
  • 8
  • 15

1 Answers1

10

It's just as described, write it using operator<< and read the state back in using operator>>.

#include <fstream>
#include <random>
#include <cassert>

int main() {
  std::mt19937 myRandomGenerator(1);

  {
    std::ofstream fout("save.txt");
    fout << myRandomGenerator;
  }

  std::ifstream fin("save.txt");
  std::mt19937 myRandomGeneratorCopy;
  fin >> myRandomGeneratorCopy;
  assert(myRandomGenerator == myRandomGeneratorCopy);
}
bames53
  • 86,085
  • 15
  • 179
  • 244