How do I fill a file with random numbers?
Basically, I'm trying to "fill" a file with 10 ^ 3 completely random numbers, so I could add them later to the binary search tree. Here is the fill function that I have been working on so far:
void populateFile(BinarySearchTree b) {
int random_integer;
srand( time( NULL ) );
std::ofstream myfile;
string line;
myfile.open ("output.txt");
myfile << "Writing this to a file: ";
for(int index=0; index<1000; index++)
{
random_integer = (rand()%1000)+1;
cout << random_integer << endl;
myfile << random_integer;
}
myfile.close();
int value;
ifstream file ("output.txt");
if (file.is_open())
{
while ( getline (file,line) )
{
value = std::stoi(line);
b.insert(value);
}
myfile.close();
}
else cout << "Unable to open file";
}
But I can't write to the file, I can just see the numbers on the console, after which the program crashes.
My second problem is this: I want to add these same numbers to a binary search tree. I already have a dd class and function, but I have no idea how to proceed. Then I want them to be able to remove them from the BST completely at random.
I already have a delete function. How is this possible? Any ideas would be much appreciated. PS: I'm new to C ++, I'm sorry if my questions sounds silly to you.
source to share
I think the solution to your problem is in @Praetorian's comment:
You probably want to
myfile << random_integer << '\n';
. Otherwise itstoi
will throwout_of_range
, which is probably the reason for the crash.
I have some general suggestions for your function.
-
Divide your function in two
- one for writing to file
- one for reading from file and filling BST. -
Don't use hard-coded filenames or globals in functions. Make them function arguments.
-
Always check the status of I / O operations. Deal with mistakes.
-
Insert a random number generator into
main
or a driver function. If you call a function that generates random numbers multiple times, you won't need to generate the random generator again.
void populateFile(int count,
std::string const& file)
{
std::ofstream myfile(file);
if (!myfile )
{
// Deal with error.
return;
}
for(int index=0; index<count; index++)
{
random_integer = (rand()%1000)+1;
myfile << random_integer << "\n";
}
}
void readFileAndBuildBST(std::string const& file,
BinarySearchTree& b)
{
std::ifstream myfile(file);
if (!myfile )
{
// Deal with error.
return;
}
int number;
while ( myfile >> number )
{
b.insert(number);
}
}
void driver()
{
// Seed the random number generator.
srand( time( NULL ) );
// Populate the file
std::string file("output.txt");
populateFile(1000, file);
// Read the data from the file and flesh out the BST.
BinarySearchTree b;
readFileAndBuildBST(file, b);
}
Withe functions split in two, you can test one function at a time. If there is a problem with one function, you can debug the problem and fix it before working with another function.
source to share