John Smith
John Smith

Reputation: 87

rand() Function not Working in Conjunction with File I/O

I am making a program to configure my wifi as I move to and from different networks frequently. I am generating a random number to be the last number in the sequence of 192.168.0.*. Now when I run the code without the file i/o the random number generates just fine, however, when I run it with the file i/o it only generates 2 or 144. Could someone tell me why this is happening and perhaps offer a solution. Thanks. Below is the code that generates the random number and checks it against the previous number used.

//initialise variables so rndm>2 and <253
int rndm, minNum=2, maxNum=253, iHistory;
bool loop=0;


while(loop==0){
  std::cout<<"One Moment please, generating random number...\n";
  //generate random number
  rndm = ((double) rand() / (RAND_MAX+1)) * (maxNum-minNum+1) + minNum;

  //Read number from history file
  ifstream inputFile("History.txt");
  string line;

  while (getline(inputFile, line)) {
      istringstream ss(line);
      string history;
      ss >> history ;
      iHistory=atoi(history.c_str());
      //If random number was used before, loop
      if(iHistory==rndm){  
          loop=0;
      }
      else{
          loop=1;            //else continue
      }
   }
}
//Write random number to file
ofstream myfile;
myfile.open ("History.txt");
myfile << rndm;
myfile.close();

std::cout<<"Random number is: "<<rndm<<"\n\n";

Upvotes: 0

Views: 167

Answers (1)

Jasin Ali
Jasin Ali

Reputation: 66

I got it to work, I just changed the random number generator.

int min = 2;
int max = 253;
int rng = 0;
srand(unsigned(time(NULL)));

rng = rand() % max;
if(rng == min-1 || rng == max-1){ rng++; }

Make sure you read up on seeds.

Upvotes: 1

Related Questions