Search code examples
c++randomstateofstream

Writing and Reading a random number state to file


I am trying to save the state of a random number generator as follows:

std::mt19937 rng
std::ofstream ofile("RngState.txt");
ofile << rng;
ofile.close();

What I observe is the state is a vector of 1248 numbers And only 624 numbers get written in the file. Is there a way to write and read all the 1248 numbers in one attempt(I guess I am trying to increase the capacity/size of ofstream).

Thanks in advance.


Solution

  • As @knivil said, state could be represented with only 624 numbers. Please tell us how did you observe 1248?

    VS 2015

    EDIT:

    I have consistent results with this code, could you run it and check too?

    #include <fstream>
    #include <random>
    #include <iostream>
    
    std::mt19937 deser(std::string fname)
    {
      std::ifstream f{fname, std::ifstream::binary};
      std::mt19937  res;
      f >> res;
      return res;
    }
    void ser(std::string fname, std::mt19937 rng)
    {
      std::ofstream f(fname, std::ofstream::binary);
      f << rng;
    }
    
    void printRand(std::mt19937 rng)
    {
      std::uniform_int_distribution<> uid{1, 100};
      std::cout << uid(rng) << std::endl;
    }
    
    int main()
    {
      auto fname{"R:\\RngState.txt"};
    
      std::mt19937 rng{std::random_device{}()};
      ser(fname, rng);
      printRand(rng);
    
      rng = deser(fname);
      printRand(rng);
    
      return 0;
    }