Program always producing same value?
the point of my program is to write the numbers 1 - 1,000,000 to a text file, generate a random number between 1 and 1,000,000, search for that line in the text file, take the value, and square it (this is just an exercise for me, it has no practical application). The problem is that whenever I run it, the value remains the same, but the rand()
function is seeded by time(0)
. I suspect that it's a garbage value but I don't know where it's coming from (I have no experience with GDB or any other standalone debuggers). Here's my source code:
#include <fstream>
#include <ctime>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv){
ofstream file("log.txt", ios::app);
ofstream programLog("programlog.dat", ios::app);
cout << "Test Start" << endl;
programLog << "Test Start" << endl;
cout << "Log file created" << endl;
programLog << "Log file created" << endl;
ifstream readFile("log.txt");
int foundNum;
std::string line = "";
unsigned int loopCount = 1000000;
unsigned int numToSearch;
const unsigned short min = 1;
const int max = 1000000;
unsigned int randomLine = 0;
for(int i = 0; i <= loopCount; i++){
file << i << endl;
}
//select random line
srand((unsigned)time(0));
while(!(randomLine > min) && !(randomLine < max)){
randomLine = (unsigned)rand();
programLog << randomLine;
int newlines = 0;
//size_t found;
while(getline(rea开发者_如何学编程dFile, line)){
if(line.find("\n") != string::npos)
newlines++;
if(newlines == randomLine)
numToSearch = atoi(line.c_str());
}
}
programLog << "Random line selected" << endl;
//read line
while(std::getline(readFile,line)){
if(atoi(line.c_str()) == numToSearch){
foundNum = numToSearch;
break;
}
else
continue;
}
//square it
const unsigned int squared = foundNum*foundNum;
programLog << squared;
readFile.close(); //end read
file.close(); //end log
programLog.close(); //end programlog
return 0;
}
You never enter the while loop as you are using:
while(!(randomLine > min) && !(randomLine < max))
while immediately evaluates to false. You should use:
while(randomLine < min || randomLine > max)
Also, why do all your variables have different types? This could lead to unintended errors. You should change them to have the same type.
randomLine
is initialized to 0, and still has that value once it reaches the while, so the loop body never executes.
精彩评论