rand()函数不能与文件I/O一起工作

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

本文关键字:一起 工作 文件 函数 不能 rand      更新时间:2023-10-16

我正在制作一个程序来配置我的wifi,因为我经常往返于不同的网络。我正在生成一个随机数,作为192.168.0.*序列中的最后一个数字。现在,当我在没有文件I/o的情况下运行代码时,随机数生成得很好,然而,当我在文件I/o的情况下运行它时,它只生成2或144。有人能告诉我为什么会发生这种情况,也许提供一个解决方案。谢谢。下面是生成随机数并将其与之前使用的数字进行检查的代码。

//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<<"nn";

我让它工作了,我只是改变了随机数生成器。

int min = 2;
int max = 253;
int rng = 0;
srand(unsigned(time(NULL)));
rng = rand() % max;
if(rng == min-1 || rng == max-1){ rng++; }

一定要好好读种子。

  • http://www.cplusplus.com/reference/cstdlib/srand/