Random Numbers on an Output Stream

I'm trying to get 100 random numbers onto an output file and I can't figure out why I'm only getting 1 number in the output.txt (the last one)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;

int main()
{
int random_integer;
srand((time_t)time(0));
for(int index=0; index<100; index++)
	{
	random_integer = (rand()%100)+1;
	cout << random_integer << endl;
	}
{
  std::ofstream myfile;
  myfile.open ("output.txt");   
  {
    myfile << "Writing this to a file: ";
    myfile <<"numbers is " << random_integer;
  }
  myfile.close();
}
system("pause");
return 0;
}
Last edited on
You need to seed the pseudo-random number generator with something other than... nine.

Typically, we seed the generator with variables that are affected by time to get seemingly random numbers.

You can do this by writing:

srand((time_t)time(0));

instead of

srand(9);

You'll have to #include <ctime> though.

The reason you only write one number to your file is because... you're only writing one number to your file.

In your for() loop, you assign a random value to random_integer one-hundred times, and you print the value each time.

Then the loop ends, you create an output file stream object, and you write random_integer to it, which still holds the last random number you generated.
To answer your first question, random_integer is just one integer whose value gets updated in your for loop. Hence it just outputs the last random number generated to the file.

To solve this problem, bring the file output statement within the for loop like cout.

For your second question, you are providing the same seed to the random generator everytime it is run (9). Hence, same set of random numbers shall be generated.

To solve it use srand( time(NULL) ) after including <ctime> header.

Your full code shall then be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <ctime> // to provide time based seed generation
using namespace std;

int main()
{
int random_integer;
srand( time( NULL ) );
std::ofstream myfile;
myfile.open ("output.txt");   
myfile << "Writing this to a file: ";
for(int index=0; index<100; index++)
	{
	random_integer = (rand()%100)+1;
	cout << random_integer << endl;
               myfile <<"numbers is " << random_integer;
	}
  myfile.close();
system("pause");
return 0;
}
Last edited on
Cool, thanks for the help! It's been racking my brain for days now.
Topic archived. No new replies allowed.