rand()函数不能与文件I/O一起工作
rand() Function not Working in Conjunction with File I/O
我正在制作一个程序来配置我的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/
相关文章:
- 如何使我的 sizeof sum 结构与空参数包一起工作
- SFINAE:它如何与派生类一起工作?
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- 尝试让条形码扫描仪与Arduino一起工作
- 从书本中学习C++无法使该程序与类一起工作
- 让类与运算符一起工作更简单的方法
- 如何使lambda与std::nullopt一起工作
- 当我使用长整型时,我的代码不起作用,它与 int 一起工作得很好
- 返回对象如何与分配运算符一起工作
- GLM :: perspective()和glm :: lookat()一起工作
- SFML OpenGL:如何同时与他们一起工作
- 使QTConcurrent ::映射与Lambdas一起工作
- 如何与C 字符串中的非ASCII字符一起工作
- 我如何适应擦除式习惯与矢量元组一起工作
- 需要帮助使 VOID 代码与总工资一起工作
- 我怎样才能让这个刽子手代码与 wxDev-C++ 一起工作
- Googletest 在 bazel test 中永远不会失败(在它应该失败的地方),但与 cmake & clion 一起工作
- 常量变量初始化仅与成员初始化列表一起工作
- feal_ptr与unique_ptr一起工作
- OpenGL Ping Pong可与一张通行证一起工作,而不是两个通行证