Random Number Generation to a text file.

Hello All,

I am a C++ beginner, so please try and keep it simple as possible! I already found an article on this website on this, but it says "I used help to figure it out", and leaves it at that. Can someone PLEASE tell me why the text file it makes is empty, and how to fill it up with the numbers it generates. Here is the code:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;

int main() {
srand(time(NULL));
float value=0.0;
ofstream myfile ("feherzaj.txt");
myfile.open ("feherzaj.txt", ios::out | ios::app );
if (myfile.is_open())
{
for (int i = 0; i < 1000; ++i) {
value = rand();
myfile << i << " " << value << "\n";
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}

My OS is Windows, and I'm working with Visual C++ Express edition(2008). I hope to hear your replys soon!
value = rand();

i belive you should use the modulo operator here to randomize a INT

change the value datatype to int from float, and then randomize a int from example: 0 to 100

value = rand()%100;

and then
 
myfile << value;


ofstream myfile ("feherzaj.txt");

you don't really need to specify the filename here it's enough with
ofstream myfile;

hope it helps
Last edited on
You're trying to open a file, that is alread open:

1
2
ofstream myfile ("feherzaj.txt"); // this constructor opens the file
myfile.open ("feherzaj.txt", ios::out | ios::app ); // then you are explicitly opening it 


I imagine you are causing an error or setting an error flag in doing this but not actually closing the file (not completely sure though).

Just remove the line: myfile.open ("feherzaj.txt", ios::out | ios::app );

Also, you're writing C++ so don't use C headers:

1
2
3
4
5
#include <iostream>
#include <cstdio> // don't need this
#include <cstdlib>
#include <ctime>
#include <fstream> 
Last edited on
Thank you both, and I will mark it as solved if that works!
Topic archived. No new replies allowed.